<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 2.0.17">
<title>RPG Maker MV 脚本记录</title>
<style>
/* normalize.css */

button, hr, input {
    overflow: visible
}

audio, canvas, progress, video {
    display: inline-block
}

progress, sub, sup {
    vertical-align: baseline
}

html {
    font-family: sans-serif;
    line-height: 1.15;
    -ms-text-size-adjust: 100%;
    -webkit-text-size-adjust: 100%
}

body {
    margin: 0
}

menu, article, aside, details, footer, header, nav, section {
    display: block
}

h1 {
    font-size: 2em;
    margin: .67em 0
}

figcaption, figure, main {
    display: block
}

figure {
    margin: 1em 40px
}

hr {
    box-sizing: content-box;
    height: 0
}

code, kbd, pre, samp {
    font-family: monospace, monospace;
    font-size: 1em
}

a {
    background-color: transparent;
    -webkit-text-decoration-skip: objects
}

a:active, a:hover {
    outline-width: 0
}

abbr[title] {
    border-bottom: none;
    text-decoration: underline;
    text-decoration: underline dotted
}

b, strong {
    font-weight: bolder
}

dfn {
    font-style: italic
}

mark {
    background-color: #ff0;
    color: #000
}

small {
    font-size: 80%
}

sub, sup {
    font-size: 75%;
    line-height: 0;
    position: relative
}

sub {
    bottom: -.25em
}

sup {
    top: -.5em
}

audio:not([controls]) {
    display: none;
    height: 0
}

img {
    border-style: none
}

svg:not(:root) {
    overflow: hidden
}

button, input, optgroup, select, textarea {
    font-family: sans-serif;
    font-size: 100%;
    line-height: 1.15;
    margin: 0
}

button, input {
}

button, select {
    text-transform: none
}

[type=submit], [type=reset], button, html [type=button] {
    -webkit-appearance: button
}

[type=button]::-moz-focus-inner, [type=reset]::-moz-focus-inner, [type=submit]::-moz-focus-inner, button::-moz-focus-inner {
    border-style: none;
    padding: 0
}

[type=button]:-moz-focusring, [type=reset]:-moz-focusring, [type=submit]:-moz-focusring, button:-moz-focusring {
    outline: ButtonText dotted 1px
}

fieldset {
    border: 1px solid silver;
    margin: 0 2px;
    padding: .35em .625em .75em
}

legend {
    box-sizing: border-box;
    color: inherit;
    display: table;
    max-width: 100%;
    padding: 0;
    white-space: normal
}

progress {
}

textarea {
    overflow: auto
}

[type=checkbox], [type=radio] {
    box-sizing: border-box;
    padding: 0
}

[type=number]::-webkit-inner-spin-button, [type=number]::-webkit-outer-spin-button {
    height: auto
}

[type=search] {
    -webkit-appearance: textfield;
    outline-offset: -2px
}

[type=search]::-webkit-search-cancel-button, [type=search]::-webkit-search-decoration {
    -webkit-appearance: none
}

::-webkit-file-upload-button {
    -webkit-appearance: button;
    font: inherit
}

summary {
    display: list-item
}

[hidden], template {
    display: none
}

/*# sourceMappingURL=normalize.min.css.map */

.toc {
    overflow-y: auto
}

.toc > .toc-list {
    overflow: hidden;
    position: relative
}

.toc > .toc-list li {
    list-style: none
}

.toc-list {
    margin: 0;
    padding-left: 10px
}

a.toc-link {
    color: currentColor;
    height: 100%
}

.is-collapsible {
    max-height: 1000px;
    overflow: hidden;
    transition: all 300ms ease-in-out
}

.is-collapsed {
    max-height: 0
}

.is-position-fixed {
    position: fixed !important;
    top: 0
}

.is-active-link {
    font-weight: 700
}

.toc-link::before {
    background-color: #EEE;
    content: ' ';
    display: inline-block;
    height: inherit;
    left: 0;
    margin-top: -1px;
    position: absolute;
    width: 2px
}

.is-active-link::before {
    background-color: #54BC4B
}

/* Activiti Specific */

body {
    color: #494d55;
    font-size: 16px;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

html, body {
    height: 100%;
    width: 100%;
    background: #f9f9f9;
    font-family: "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif;
    color: #484848
}

.page-wrapper {
    min-height: 100%;
    /* equal to footer height */
    margin-bottom: -50px;
}

.page-wrapper:after {
    content: "";
    display: block;
    height: 50px;
}

#header {
    top: 0;
    z-index: 100000;
    width: 100%;
}

#header > h1 {
    background-image: radial-gradient(circle, #1280e1 0%, #002069 100%);
    color: #f9f9f9;
    padding: 20px 0 20px 20px;
    font-size: 3em;
    font-weight: 800;
    line-height: 1.1;
    margin: 0;
}

#header > h1:before {
    background-size: 180px 54px;
    background-repeat: no-repeat;
    width: 337px;
    height: 54px;
    display: inline-block;
    content: '';
    margin-right: 30px;
}

#author {
    margin-left: 25%;
    font-size: 40px;
}

#content {
    margin: 0 0 0 27%;
    padding: 10px 40px 0 20px;
    padding-right: 40px;
    line-height: 1.7;
    width: 67%;
    overflow-x: auto;
}

h2, h3, h4, h5, h6 {
    color: #00345a;
}

h2 {
    font-size: 26px;
    margin-top: 0;
    margin-bottom: 20px;
    font-weight: bold;
    padding-bottom: 10px;
    border-bottom: 1px solid #d7d7d7;
}

h3 {
    font-size: 18px;
    margin-top: 0;
    margin-bottom: 0;
    font-weight: bold;
    padding-bottom: 10px;
    /*border-bottom: 1px solid #d7d7d7;*/
}

h4 {
    font-size: 16px;
    font-weight: bold;
}

h5 {
    font-size: 14px;
    font-weight: bold;
}

h6, h7 {
    font-size: 14px;
    font-weight: bold;
    margin-top: 0;
    margin-bottom: 0;
}

.sect1, .sect2 {
    margin-bottom: 20px;
}

.clear {
    clear: both;
}

.note, .listingblock, .literalblock {
    overflow-x: auto;
    position: relative;
    width: 100%;
    margin: 0 0 15px 0;
    background-color: #F0F0F0;
    border-left: 3px solid #00a9e5;
    display: inline-flex;
    padding-left: 10px;
}

table.tableblock {
    width: 100%;
    max-width: 100%;
    margin-bottom: 20px;
    background-color: transparent;
    border-spacing: 0;
    border-collapse: collapse;
    border: 1px solid #ddd;
    table-layout: fixed;
}

table.tableblock > caption + thead > tr:first-child > td, table.tableblock > caption + thead > tr:first-child > th, table.tableblock > colgroup + thead > tr:first-child > td, table.tableblock > colgroup + thead > tr:first-child > th, table.tableblock > thead:first-child > tr:first-child > td, table.tableblock > thead:first-child > tr:first-child > th {
    border-top: 0;
}

table.tableblock > thead > tr > th {
    border-bottom-color: #8bd6d8;
}

table.tableblock > thead > tr > th {
    vertical-align: bottom;
    border-bottom: 1px solid #ddd;
}

table.tableblock > tbody > tr > td, table.tableblock > tbody > tr > th, table.tableblock > tfoot > tr > td, table.tableblock > tfoot > tr > th, table.tableblock > thead > tr > td, table.tableblock > thead > tr > th {
    padding: 8px;
    line-height: 1.42857143;
    vertical-align: top;
    border-top: 1px solid #ddd;
}

th {
    text-align: left;
}

table.tableblock > tbody > tr:nth-of-type(odd) {
    background-color: #f5f5f5;
}

table.tableblock > tbody > tr:nth-of-type(odd) {
    background-color: #f9f9f9;
}

td > p {
    margin: 0;
}

td.content {
    white-space: normal;
}

pre, td, th {
    white-space: pre-wrap;
    white-space: -moz-pre-wrap;
    white-space: -pre-wrap;
    white-space: -o-pre-wrap;
    word-wrap: break-word;
}

img {
    max-width: 100%;
}

a {
    color: #007387;
}

a:hover {
    color: #004c59;
}

#toc-parent {
    width: 23%;
    float: left;
    height: 100%;
    overflow-y: auto;
    position: fixed;
    padding: 10px;
    border-right: 1px solid #ccc;
}

#generated-toc {
    width: 100%;
    height: 100%;
    font-size: 16px;
}

.toc-link {
    text-decoration: none;
}

.toc-list {
    margin: 0 20px 0 10px;
}

.toc-list-item {
    padding: 4px 0 4px 0;
}


div.sect5 p {
    margin-top: 0;
    margin-bottom: 0;
}

div.sect5 code {
    font-family: "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif;
}

.warning td.icon {
    background: url('../images/warning.png') no-repeat 0 45%;
    width: 70px;
}

.warning td.icon .title {
    visibility: hidden;
}

.important td.icon {
    background: url('../images/important.png') no-repeat 0 45%;
    width: 70px;
}

.important td.icon .title {
    visibility: hidden;
}

.note td.icon {
    background: url('../images/note.png') no-repeat 0 45%;
    width: 60px;
}

.note td.icon .title {
    visibility: hidden;
}

.conum[data-value] {
    display: inline-block;
    color: #fff !important;
    background-color: rgba(0, 0, 0, 0.8);
    -webkit-border-radius: 100px;
    border-radius: 100px;
    text-align: center;
    width: 1.67em;
    height: 1.67em;
    font-size: 0.75em;
    line-height: 1.67em;
    font-family: "Open Sans", "Sans", sans-serif;
    font-style: normal;
    font-weight: bold;
}

.conum[data-value] + b {
    display: none;
}

.conum[data-value]:after {
    content: attr(data-value);
}

*:not(pre) > code {
    font-size: .9375em;
    font-weight: normal;
    color: rgba(0, 0, 0, 0.9);
    background-color: #eaeaef;
    -webkit-border-radius: 4px;
    border-radius: 4px;
    line-height: 1.45;
    padding: 0.1em 0.5ex;
    word-spacing: -.15em;
}

.admonitionblock {
    background: #f2f2f3;
    padding: 10px;
    min-height: 80px;
    margin: 15px 0;
    border-radius: 5px;
    position: relative;
}

h1 {
    filter: alpha(Opacity=93);
    -moz-opacity: 0.93;
    opacity: 0.93;
}

.choose-version {
    position: fixed;
    left: 40px;
    top: 40px;
    z-index: 9999;
}

.line-through {
    text-decoration: line-through;
}


</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script type="text/javascript">
    // https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.11.1/tocbot.min.js
    !function(e){var t={};function n(o){if(t[o])return t[o].exports;var l=t[o]={i:o,l:!1,exports:{}};return e[o].call(l.exports,l,l.exports,n),l.l=!0,l.exports}n.m=e,n.c=t,n.d=function(e,t,o){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:o})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(n.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var l in e)n.d(o,l,function(t){return e[t]}.bind(null,l));return o},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t,n){(function(o){var l,r,i;!function(o,s){r=[],l=function(e){"use strict";var t,o,l,r=n(2),i={},s={},c=n(3),a=n(4),u=!!(e&&e.document&&e.document.querySelector&&e.addEventListener);if("undefined"==typeof window&&!u)return;var d=Object.prototype.hasOwnProperty;function f(e,t,n){var o,l;return t||(t=250),function(){var r=n||this,i=+new Date,s=arguments;o&&i<o+t?(clearTimeout(l),l=setTimeout(function(){o=i,e.apply(r,s)},t)):(o=i,e.apply(r,s))}}return s.destroy=function(){if(!i.skipRendering)try{document.querySelector(i.tocSelector).innerHTML=""}catch(e){console.warn("Element not found: "+i.tocSelector)}i.scrollContainer&&document.querySelector(i.scrollContainer)?(document.querySelector(i.scrollContainer).removeEventListener("scroll",this._scrollListener,!1),document.querySelector(i.scrollContainer).removeEventListener("resize",this._scrollListener,!1),t&&document.querySelector(i.scrollContainer).removeEventListener("click",this._clickListener,!1)):(document.removeEventListener("scroll",this._scrollListener,!1),document.removeEventListener("resize",this._scrollListener,!1),t&&document.removeEventListener("click",this._clickListener,!1))},s.init=function(e){if(u&&(i=function(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var o in n)d.call(n,o)&&(e[o]=n[o])}return e}(r,e||{}),this.options=i,this.state={},i.scrollSmooth&&(i.duration=i.scrollSmoothDuration,i.offset=i.scrollSmoothOffset,s.scrollSmooth=n(5).initSmoothScrolling(i)),t=c(i),o=a(i),this._buildHtml=t,this._parseContent=o,s.destroy(),null!==(l=o.selectHeadings(i.contentSelector,i.headingSelector)))){var m=o.nestHeadingsArray(l).nest;i.skipRendering||t.render(i.tocSelector,m),this._scrollListener=f(function(e){t.updateToc(l);var n=e&&e.target&&e.target.scrollingElement&&0===e.target.scrollingElement.scrollTop;(e&&(0===e.eventPhase||null===e.currentTarget)||n)&&(t.updateToc(l),i.scrollEndCallback&&i.scrollEndCallback(e))},i.throttleTimeout),this._scrollListener(),i.scrollContainer&&document.querySelector(i.scrollContainer)?(document.querySelector(i.scrollContainer).addEventListener("scroll",this._scrollListener,!1),document.querySelector(i.scrollContainer).addEventListener("resize",this._scrollListener,!1)):(document.addEventListener("scroll",this._scrollListener,!1),document.addEventListener("resize",this._scrollListener,!1));var h=null;return this._clickListener=f(function(e){i.scrollSmooth&&t.disableTocAnimation(e),t.updateToc(l),h&&clearTimeout(h),h=setTimeout(function(){t.enableTocAnimation()},i.scrollSmoothDuration)},i.throttleTimeout),i.scrollContainer&&document.querySelector(i.scrollContainer)?document.querySelector(i.scrollContainer).addEventListener("click",this._clickListener,!1):document.addEventListener("click",this._clickListener,!1),this}},s.refresh=function(e){s.destroy(),s.init(e||this.options)},e.tocbot=s,s}(o),void 0===(i="function"==typeof l?l.apply(t,r):l)||(e.exports=i)}(void 0!==o?o:this.window||this.global)}).call(this,n(1))},function(e,t){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t){e.exports={tocSelector:".js-toc",contentSelector:".js-toc-content",headingSelector:"h1, h2, h3",ignoreSelector:".js-toc-ignore",hasInnerContainers:!1,linkClass:"toc-link",extraLinkClasses:"",activeLinkClass:"is-active-link",listClass:"toc-list",extraListClasses:"",isCollapsedClass:"is-collapsed",collapsibleClass:"is-collapsible",listItemClass:"toc-list-item",activeListItemClass:"is-active-li",collapseDepth:0,scrollSmooth:!0,scrollSmoothDuration:420,scrollSmoothOffset:0,scrollEndCallback:function(e){},headingsOffset:1,throttleTimeout:50,positionFixedSelector:null,positionFixedClass:"is-position-fixed",fixedSidebarOffset:"auto",includeHtml:!1,onClick:function(e){},orderedList:!0,scrollContainer:null,skipRendering:!1,headingLabelCallback:!1,ignoreHiddenElements:!1,headingObjectCallback:null,basePath:""}},function(e,t){e.exports=function(e){var t=[].forEach,n=[].some,o=document.body,l=!0,r=" ";function i(n,o){var l=o.appendChild(function(n){var o=document.createElement("li"),l=document.createElement("a");e.listItemClass&&o.setAttribute("class",e.listItemClass);e.onClick&&(l.onclick=e.onClick);e.includeHtml&&n.childNodes.length?t.call(n.childNodes,function(e){l.appendChild(e.cloneNode(!0))}):l.textContent=n.textContent;return l.setAttribute("href",e.basePath+"#"+n.id),l.setAttribute("class",e.linkClass+r+"node-name--"+n.nodeName+r+e.extraLinkClasses),o.appendChild(l),o}(n));if(n.children.length){var c=s(n.isCollapsed);n.children.forEach(function(e){i(e,c)}),l.appendChild(c)}}function s(t){var n=e.orderedList?"ol":"ul",o=document.createElement(n),l=e.listClass+r+e.extraListClasses;return t&&(l+=r+e.collapsibleClass,l+=r+e.isCollapsedClass),o.setAttribute("class",l),o}return{enableTocAnimation:function(){l=!0},disableTocAnimation:function(t){var n=t.target||t.srcElement;"string"==typeof n.className&&-1!==n.className.indexOf(e.linkClass)&&(l=!1)},render:function(e,t){var n=s(!1);t.forEach(function(e){i(e,n)});var o=document.querySelector(e);if(null!==o)return o.firstChild&&o.removeChild(o.firstChild),0===t.length?o:o.appendChild(n)},updateToc:function(i){var s;s=e.scrollContainer&&document.querySelector(e.scrollContainer)?document.querySelector(e.scrollContainer).scrollTop:document.documentElement.scrollTop||o.scrollTop,e.positionFixedSelector&&function(){var t;t=e.scrollContainer&&document.querySelector(e.scrollContainer)?document.querySelector(e.scrollContainer).scrollTop:document.documentElement.scrollTop||o.scrollTop;var n=document.querySelector(e.positionFixedSelector);"auto"===e.fixedSidebarOffset&&(e.fixedSidebarOffset=document.querySelector(e.tocSelector).offsetTop),t>e.fixedSidebarOffset?-1===n.className.indexOf(e.positionFixedClass)&&(n.className+=r+e.positionFixedClass):n.className=n.className.split(r+e.positionFixedClass).join("")}();var c,a=i;if(l&&null!==document.querySelector(e.tocSelector)&&a.length>0){n.call(a,function(t,n){return function t(n){var o=0;return n!==document.querySelector(e.contentSelector&&null!=n)&&(o=n.offsetTop,e.hasInnerContainers&&(o+=t(n.offsetParent))),o}(t)>s+e.headingsOffset+10?(c=a[0===n?n:n-1],!0):n===a.length-1?(c=a[a.length-1],!0):void 0});var u=document.querySelector(e.tocSelector).querySelectorAll("."+e.linkClass);t.call(u,function(t){t.className=t.className.split(r+e.activeLinkClass).join("")});var d=document.querySelector(e.tocSelector).querySelectorAll("."+e.listItemClass);t.call(d,function(t){t.className=t.className.split(r+e.activeListItemClass).join("")});var f=document.querySelector(e.tocSelector).querySelector("."+e.linkClass+".node-name--"+c.nodeName+'[href="'+e.basePath+"#"+c.id.replace(/([ #;&,.+*~':"!^$[\]()=>|/@])/g,"\\$1")+'"]');-1===f.className.indexOf(e.activeLinkClass)&&(f.className+=r+e.activeLinkClass);var m=f.parentNode;m&&-1===m.className.indexOf(e.activeListItemClass)&&(m.className+=r+e.activeListItemClass);var h=document.querySelector(e.tocSelector).querySelectorAll("."+e.listClass+"."+e.collapsibleClass);t.call(h,function(t){-1===t.className.indexOf(e.isCollapsedClass)&&(t.className+=r+e.isCollapsedClass)}),f.nextSibling&&-1!==f.nextSibling.className.indexOf(e.isCollapsedClass)&&(f.nextSibling.className=f.nextSibling.className.split(r+e.isCollapsedClass).join("")),function t(n){return-1!==n.className.indexOf(e.collapsibleClass)&&-1!==n.className.indexOf(e.isCollapsedClass)?(n.className=n.className.split(r+e.isCollapsedClass).join(""),t(n.parentNode.parentNode)):n}(f.parentNode.parentNode)}}}}},function(e,t){e.exports=function(e){var t=[].reduce;function n(e){return e[e.length-1]}function o(t){if(!(t instanceof window.HTMLElement))return t;if(e.ignoreHiddenElements&&(!t.offsetHeight||!t.offsetParent))return null;var n={id:t.id,children:[],nodeName:t.nodeName,headingLevel:function(e){return+e.nodeName.split("H").join("")}(t),textContent:e.headingLabelCallback?String(e.headingLabelCallback(t.textContent)):t.textContent.trim()};return e.includeHtml&&(n.childNodes=t.childNodes),e.headingObjectCallback?e.headingObjectCallback(n,t):n}return{nestHeadingsArray:function(l){return t.call(l,function(t,l){var r=o(l);return r&&function(t,l){for(var r=o(t),i=r.headingLevel,s=l,c=n(s),a=i-(c?c.headingLevel:0);a>0;)(c=n(s))&&void 0!==c.children&&(s=c.children),a--;i>=e.collapseDepth&&(r.isCollapsed=!0),s.push(r)}(r,t.nest),t},{nest:[]})},selectHeadings:function(t,n){var o=n;e.ignoreSelector&&(o=n.split(",").map(function(t){return t.trim()+":not("+e.ignoreSelector+")"}));try{return document.querySelector(t).querySelectorAll(o)}catch(e){return console.warn("Element not found: "+t),null}}}}},function(e,t){function n(e,t){var n=window.pageYOffset,o={duration:t.duration,offset:t.offset||0,callback:t.callback,easing:t.easing||d},l=document.querySelector('[id="'+decodeURI(e).split("#").join("")+'"]'),r=typeof e==="string"?o.offset+(e?l&&l.getBoundingClientRect().top||0:-(document.documentElement.scrollTop||document.body.scrollTop)):e,i=typeof o.duration==="function"?o.duration(r):o.duration,s,c;function a(e){c=e-s;window.scrollTo(0,o.easing(c,n,r,i));if(c<i){requestAnimationFrame(a)}else{u()}}function u(){if(window.scrollTo(0,n+r),"function"==typeof o.callback){o.callback()}}function d(e,t,n,o){return(e/=o/2)<1?n/2*e*e+t:-n/2*(--e*(e-2)-1)+t}requestAnimationFrame(function(e){s=e;a(e)})}t.initSmoothScrolling=function(e){document.documentElement.style;var t=e.duration,o=e.offset,l=location.hash?r(location.href):location.href;function r(e){return e.slice(0,e.lastIndexOf("#"))}!function(){document.body.addEventListener("click",function(i){if(!function(e){return"a"===e.tagName.toLowerCase()&&(e.hash.length>0||"#"===e.href.charAt(e.href.length-1))&&(r(e.href)===l||r(e.href)+"#"===l)}(i.target)||i.target.className.indexOf("no-smooth-scroll")>-1||"#"===i.target.href.charAt(i.target.href.length-2)&&"!"===i.target.href.charAt(i.target.href.length-1)||-1===i.target.className.indexOf(e.linkClass))return;n(i.target.hash,{duration:t,offset:o,callback:function(){!function(e){var t=document.getElementById(e.substring(1));t&&(/^(?:a|select|input|button|textarea)$/i.test(t.tagName)||(t.tabIndex=-1),t.focus())}(i.target.hash)}})},!1)}()}}]);
</script>

<script type="text/javascript">

    var generateToc = function () {
        var readyState = document.readyState;
        if (readyState === 'interactive' || readyState == 'complete') {

            var headerSize = 140;

            var tocParentNode = document.createElement("div");
            tocParentNode.setAttribute("id", "toc-parent");

            var generatedTocNode = document.createElement("div");
            generatedTocNode.setAttribute("id", "generated-toc");
            tocParentNode.appendChild(generatedTocNode);

            var contentNode = document.getElementById("content");
            contentNode.parentNode.insertBefore(tocParentNode, contentNode);

            var clearNode = document.createElement("div");
            clearNode.setAttribute("class", "clear");
            contentNode.parentNode.appendChild(clearNode);

            tocbot.init({
                tocSelector: '#generated-toc',
                contentSelector: '#content',
                headingSelector: 'h2, h3, h4, h5',
                headingsOffset: headerSize,
                smoothScrollOptions: {
                    easing: 'easeInOutCubic',
                    offset: headerSize,
                    speed: 300, // animation duration.
                    updateURL: true
                },
                collapseDepth: 0
            });

        } else {
            window.setTimeout(function () {
                generateToc();
            }, 50);
        }

    }
    generateToc();

</script>

<div class="choose-version">
    <select id="choose-version" onchange="chooseVersion(this.value)">
        <option value="rmmv">RPG Maker MV 文件结构</option>
        <option value="rmmv-window">RPG Maker MV 窗口速查表</option>
        <option value="rmmv-js">RPG Maker MV JS 脚本记录</option>
    </select>
</div>

<script type="text/javascript">
    var initVersion = function () {
        var list = window.location.pathname.split('/');
        document.getElementById('choose-version').value = list[list.length - 2];
    };
    initVersion();

    var chooseVersion = function (obj) {
        window.location.href = '../' + obj;
    }
</script>
</head>
<body class="book">
<div id="header">
<h1>RPG Maker MV 脚本记录</h1>
</div>
<div id="content">
<div class="sect1">
<h2 id="_管理器_rpg_managers_js">管理器: rpg_managers.js</h2>
<div class="sectionbody">
<div class="olist arabic">
<ol class="arabic">
<li>
<p>DataManager: 数据管理器</p>
</li>
<li>
<p>ConfigManager: 配置管理器</p>
</li>
<li>
<p>StorageManager: 存储管理器</p>
</li>
<li>
<p>ImageManager: 图像管理器</p>
</li>
<li>
<p>AudioManager: 音频管理器</p>
</li>
<li>
<p>SoundManager: 声音管理器</p>
</li>
<li>
<p>TextManager: 文本管理器</p>
</li>
<li>
<p>SceneManager: 场景管理器</p>
</li>
<li>
<p>BattleManager: 战斗管理器</p>
</li>
<li>
<p>PluginManager: 插件管理器</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-javascript" data-lang="javascript">//=============================================================================
// rpg_managers.js v1.6.1
//=============================================================================

//-----------------------------------------------------------------------------
// 数据管理器
// DataManager
//
// 管理数据和游戏对象的静态类。
// The static class that manages the database and game objects.

function DataManager() {
    throw new Error('This is a static class');
}

var $dataActors       = null;  // 角色数据 
var $dataClasses      = null;  // 职业数据 
var $dataSkills       = null;  // 技能数据 
var $dataItems        = null;  // 物品数据 
var $dataWeapons      = null;  // 武器数据 
var $dataArmors       = null;  // 护甲数据 
var $dataEnemies      = null;  // 敌人数据 
var $dataTroops       = null;  // 敌群数据 
var $dataStates       = null;  // 状态数据 
var $dataAnimations   = null;  // 动画数据 
var $dataTilesets     = null;  // 图块数据 
var $dataCommonEvents = null;  // 公共事件数据 
var $dataSystem       = null;  // 系统数据 
var $dataMapInfos     = null;  // 地图信息数据 
var $dataMap          = null;  // 地图数据 
var $gameTemp         = null;  // 游戏临时 
var $gameSystem       = null;  // 游戏系统 
var $gameScreen       = null;  // 游戏画面 
var $gameTimer        = null;  // 游戏计时器 
var $gameMessage      = null;  // 游戏消息 
var $gameSwitches     = null;  // 游戏开关 
var $gameVariables    = null;  // 游戏变量 
var $gameSelfSwitches = null;  // 游戏独立开关 
var $gameActors       = null;  // 游戏角色 
var $gameParty        = null;  // 游戏队伍 
var $gameTroop        = null;  // 游戏敌群 
var $gameMap          = null;  // 游戏地图 
var $gamePlayer       = null;  // 游戏玩家 
var $testEvent        = null;  // 测试事件 

DataManager._globalId       = 'RPGMV';  //全局 ID 
DataManager._lastAccessedId = 1;  // 上次访问 ID，指存档的 ID 
DataManager._errorUrl       = null;  //错误链接 

DataManager._databaseFiles = [
    { name: '$dataActors',       src: 'Actors.json'       },  // 角色 
    { name: '$dataClasses',      src: 'Classes.json'      },  // 职业 
    { name: '$dataSkills',       src: 'Skills.json'       },  // 技能 
    { name: '$dataItems',        src: 'Items.json'        },  // 物品 
    { name: '$dataWeapons',      src: 'Weapons.json'      },  // 武器 
    { name: '$dataArmors',       src: 'Armors.json'       },  // 护甲 
    { name: '$dataEnemies',      src: 'Enemies.json'      },  // 敌人 
    { name: '$dataTroops',       src: 'Troops.json'       },  // 敌群 
    { name: '$dataStates',       src: 'States.json'       },  // 状态 
    { name: '$dataAnimations',   src: 'Animations.json'   },  // 动画 
    { name: '$dataTilesets',     src: 'Tilesets.json'     },  // 图块 
    { name: '$dataCommonEvents', src: 'CommonEvents.json' },  // 公共事件 
    { name: '$dataSystem',       src: 'System.json'       },  // 系统 
    { name: '$dataMapInfos',     src: 'MapInfos.json'     }   // 地图信息 
];

/* 加载数据库 */
DataManager.loadDatabase = function() {
    var test = this.isBattleTest() || this.isEventTest();
    var prefix = test ? 'Test_' : '';
    for (var i = 0; i &lt; this._databaseFiles.length; i) {
        var name = this._databaseFiles[i].name;
        var src = this._databaseFiles[i].src;
        this.loadDataFile(name, prefix + src);
    }
    if (this.isEventTest()) {
        this.loadDataFile('$testEvent', prefix + 'Event.json');
    }
};

/* 加载数据文件 */
DataManager.loadDataFile = function(name, src) {
    var xhr = new XMLHttpRequest();
    var url = 'data/' + src;
    xhr.open('GET', url);
    xhr.overrideMimeType('application/json');
    xhr.onload = function() {
        if (xhr.status &lt; 400) {
            window[name] = JSON.parse(xhr.responseText);
            DataManager.onLoad(window[name]);
        }
    };
    xhr.onerror = this._mapLoader || function() {
        DataManager._errorUrl = DataManager._errorUrl || url;
    };
    window[name] = null;
    xhr.send();
};

/* 数据库是否加载完毕 */
DataManager.isDatabaseLoaded = function() {
    this.checkError();
    for (var i = 0; i &lt; this._databaseFiles.length; i) {
        if (!window[this._databaseFiles[i].name]) {
            return false;
        }
    }
    return true;
};

/* 加载地图数据 */
DataManager.loadMapData = function(mapId) {
    if (mapId &gt; 0) {
        var filename = 'Map%1.json'.format(mapId.padZero(3));
        this._mapLoader = ResourceHandler.createLoader('data/' + filename, this.loadDataFile.bind(this, '$dataMap', filename));
        this.loadDataFile('$dataMap', filename);
    } else {
        this.makeEmptyMap();
    }
};

/* 制作空地图 */
DataManager.makeEmptyMap = function() {
    $dataMap = {};
    $dataMap.data = [];
    $dataMap.events = [];
    $dataMap.width = 100;
    $dataMap.height = 100;
    $dataMap.scrollType = 3;
};

/* 地图是否加载 */
DataManager.isMapLoaded = function() {
    this.checkError();
    return !!$dataMap;
};

/* 当加载 */
DataManager.onLoad = function(object) {
    var array;
    if (object === $dataMap) {
        this.extractMetadata(object);
        array = object.events;
    } else {
        array = object;
    }
    if (Array.isArray(array)) {
        for (var i = 0; i &lt; array.length; i) {
            var data = array[i];
            if (data &amp;&amp; data.note !== undefined) {
                this.extractMetadata(data);
            }
        }
    }
    if (object === $dataSystem) {
        Decrypter.hasEncryptedImages = !!object.hasEncryptedImages;
        Decrypter.hasEncryptedAudio = !!object.hasEncryptedAudio;
        Scene_Boot.loadSystemImages();
    }
};

/* 提取元数据 
 * 解析 &lt;key:value&gt; 或 &lt;key&gt; 格式的字符串，一般用于备注。
 */
DataManager.extractMetadata = function(data) {
    var re = /&lt;([^&lt;&gt;:]+)(:?)([^&gt;]*)&gt;/g;
    data.meta = {};
    for (;;) {
        var match = re.exec(data.note);
        if (match) {
            if (match[2] === ':') {
                data.meta[match[1]] = match[3];
            } else {
                data.meta[match[1]] = true;
            }
        } else {
            break;
        }
    }
};

/* 检测错误 */
DataManager.checkError = function() {
    if (DataManager._errorUrl) {
        throw new Error('Failed to load: ' + DataManager._errorUrl);
    }
};

/* 是否是战斗测试 */
DataManager.isBattleTest = function() {
    return Utils.isOptionValid('btest');
};

/* 是否是事件测试 */
DataManager.isEventTest = function() {
    return Utils.isOptionValid('etest');
};

/* 是否是技能 */
DataManager.isSkill = function(item) {
    return item &amp;&amp; $dataSkills.contains(item);
};

/* 是否是物品 */
DataManager.isItem = function(item) {
    return item &amp;&amp; $dataItems.contains(item);
};

/* 是否是武器 */
DataManager.isWeapon = function(item) {
    return item &amp;&amp; $dataWeapons.contains(item);
};

/* 是否是护甲 */
DataManager.isArmor = function(item) {
    return item &amp;&amp; $dataArmors.contains(item);
};

/* 创建游戏对象 */
DataManager.createGameObjects = function() {
    $gameTemp          = new Game_Temp();
    $gameSystem        = new Game_System();
    $gameScreen        = new Game_Screen();
    $gameTimer         = new Game_Timer();
    $gameMessage       = new Game_Message();
    $gameSwitches      = new Game_Switches();
    $gameVariables     = new Game_Variables();
    $gameSelfSwitches  = new Game_SelfSwitches();
    $gameActors        = new Game_Actors();
    $gameParty         = new Game_Party();
    $gameTroop         = new Game_Troop();
    $gameMap           = new Game_Map();
    $gamePlayer        = new Game_Player();
};

/* 设置新游戏 */
DataManager.setupNewGame = function() {
    this.createGameObjects();
    this.selectSavefileForNewGame();
    $gameParty.setupStartingMembers();
    $gamePlayer.reserveTransfer($dataSystem.startMapId,
        $dataSystem.startX, $dataSystem.startY);
    Graphics.frameCount = 0;
};

/* 设置战斗测试 */
DataManager.setupBattleTest = function() {
    this.createGameObjects();
    $gameParty.setupBattleTest();
    BattleManager.setup($dataSystem.testTroopId, true, false);
    BattleManager.setBattleTest(true);
    BattleManager.playBattleBgm();
};

/* 设置事件测试 */
DataManager.setupEventTest = function() {
    this.createGameObjects();
    this.selectSavefileForNewGame();
    $gameParty.setupStartingMembers();
    $gamePlayer.reserveTransfer(-1, 8, 6);
    $gamePlayer.setTransparent(false);
};

/* 加载全局信息 */
DataManager.loadGlobalInfo = function() {
    var json;
    try {
        json = StorageManager.load(0);
    } catch (e) {
        console.error(e);
        return [];
    }
    if (json) {
        var globalInfo = JSON.parse(json);
        for (var i = 1; i &lt;= this.maxSavefiles(); i) {
            if (!StorageManager.exists(i)) {
                delete globalInfo[i];
            }
        }
        return globalInfo;
    } else {
        return [];
    }
};

/* 保存全局信息 */
DataManager.saveGlobalInfo = function(info) {
    StorageManager.save(0, JSON.stringify(info));
};

/*是否这个游戏文件 */
DataManager.isThisGameFile = function(savefileId) {
    var globalInfo = this.loadGlobalInfo();
    if (globalInfo &amp;&amp; globalInfo[savefileId]) {
        if (StorageManager.isLocalMode()) {
            return true;
        } else {
            var savefile = globalInfo[savefileId];
            return (savefile.globalId === this._globalId &amp;&amp;
                    savefile.title === $dataSystem.gameTitle);
        }
    } else {
        return false;
    }
};

/* 是否存在存档 */
DataManager.isAnySavefileExists = function() {
    var globalInfo = this.loadGlobalInfo();
    if (globalInfo) {
        for (var i = 1; i &lt; globalInfo.length; i) {
            if (this.isThisGameFile(i)) {
                return true;
            }
        }
    }
    return false;
};

/* 最新的存档 ID */
DataManager.latestSavefileId = function() {
    var globalInfo = this.loadGlobalInfo();
    var savefileId = 1;
    var timestamp = 0;
    if (globalInfo) {
        for (var i = 1; i &lt; globalInfo.length; i) {
            if (this.isThisGameFile(i) &amp;&amp; globalInfo[i].timestamp &gt; timestamp) {
                timestamp = globalInfo[i].timestamp;
                savefileId = i;
            }
        }
    }
    return savefileId;
};

/* 加载所有存档图像 */
DataManager.loadAllSavefileImages = function() {
    var globalInfo = this.loadGlobalInfo();
    if (globalInfo) {
        for (var i = 1; i &lt; globalInfo.length; i) {
            if (this.isThisGameFile(i)) {
                var info = globalInfo[i];
                this.loadSavefileImages(info);
            }
        }
    }
};

/* 加载存档图像 */
DataManager.loadSavefileImages = function(info) {
    if (info.characters) {
        for (var i = 0; i &lt; info.characters.length; i) {
            ImageManager.reserveCharacter(info.characters[i][0]);
        }
    }
    if (info.faces) {
        for (var j = 0; j &lt; info.faces.length; j) {
            ImageManager.reserveFace(info.faces[j][0]);
        }
    }
};

/* 最大存档数 */
DataManager.maxSavefiles = function() {
    return 20;
};

/* 保存游戏 */
DataManager.saveGame = function(savefileId) {
    try {
        StorageManager.backup(savefileId);
        return this.saveGameWithoutRescue(savefileId);
    } catch (e) {
        console.error(e);
        try {
            StorageManager.remove(savefileId);
            StorageManager.restoreBackup(savefileId);
        } catch (e2) {
        }
        return false;
    }
};

/* 加载游戏 */
DataManager.loadGame = function(savefileId) {
    try {
        return this.loadGameWithoutRescue(savefileId);
    } catch (e) {
        console.error(e);
        return false;
    }
};

/* 加载存档信息 */
DataManager.loadSavefileInfo = function(savefileId) {
    var globalInfo = this.loadGlobalInfo();
    return (globalInfo &amp;&amp; globalInfo[savefileId]) ? globalInfo[savefileId] : null;
};

/* 上次访问的存档 ID */
DataManager.lastAccessedSavefileId = function() {
    return this._lastAccessedId;
};

/* 无异常处理的保存游戏
 * 函数名的 rescue 指 ruby 的 begin rescue，相当于 js 的 try catch，也就是异常处理。
 */
DataManager.saveGameWithoutRescue = function(savefileId) {
    var json = JsonEx.stringify(this.makeSaveContents());
    if (json.length &gt;= 200000) {
        console.warn('Save data too big!');
    }
    StorageManager.save(savefileId, json);
    this._lastAccessedId = savefileId;
    var globalInfo = this.loadGlobalInfo() || [];
    globalInfo[savefileId] = this.makeSavefileInfo();
    this.saveGlobalInfo(globalInfo);
    return true;
};

/* 无异常处理的加载游戏 */
DataManager.loadGameWithoutRescue = function(savefileId) {
    var globalInfo = this.loadGlobalInfo();
    if (this.isThisGameFile(savefileId)) {
        var json = StorageManager.load(savefileId);
        this.createGameObjects();
        this.extractSaveContents(JsonEx.parse(json));
        this._lastAccessedId = savefileId;
        return true;
    } else {
        return false;
    }
};

/* 为新游戏选择存档 */
DataManager.selectSavefileForNewGame = function() {
    var globalInfo = this.loadGlobalInfo();
    this._lastAccessedId = 1;
    if (globalInfo) {
        var numSavefiles = Math.max(0, globalInfo.length - 1);
        if (numSavefiles &lt; this.maxSavefiles()) {
            this._lastAccessedId = numSavefiles + 1;
        } else {
            var timestamp = Number.MAX_VALUE;
            for (var i = 1; i &lt; globalInfo.length; i) {
                if (!globalInfo[i]) {
                    this._lastAccessedId = i;
                    break;
                }
                if (globalInfo[i].timestamp &lt; timestamp) {
                    timestamp = globalInfo[i].timestamp;
                    this._lastAccessedId = i;
                }
            }
        }
    }
};

/* 制作存档信息 */
DataManager.makeSavefileInfo = function() {
    var info = {};
    info.globalId   = this._globalId;
    info.title      = $dataSystem.gameTitle;
    info.characters = $gameParty.charactersForSavefile();
    info.faces      = $gameParty.facesForSavefile();
    info.playtime   = $gameSystem.playtimeText();
    info.timestamp  = Date.now();
    return info;
};

/* 制作保存内容 */
DataManager.makeSaveContents = function() {
    // 保存的数据不包含 $gameTemp、$gameMessage 和 $gameTroop。 
    // A save data does not contain $gameTemp, $gameMessage, and $gameTroop.
    var contents = {};
    contents.system       = $gameSystem;
    contents.screen       = $gameScreen;
    contents.timer        = $gameTimer;
    contents.switches     = $gameSwitches;
    contents.variables    = $gameVariables;
    contents.selfSwitches = $gameSelfSwitches;
    contents.actors       = $gameActors;
    contents.party        = $gameParty;
    contents.map          = $gameMap;
    contents.player       = $gamePlayer;
    return contents;
};

/* 提取保存内容 */
DataManager.extractSaveContents = function(contents) {
    $gameSystem        = contents.system;
    $gameScreen        = contents.screen;
    $gameTimer         = contents.timer;
    $gameSwitches      = contents.switches;
    $gameVariables     = contents.variables;
    $gameSelfSwitches  = contents.selfSwitches;
    $gameActors        = contents.actors;
    $gameParty         = contents.party;
    $gameMap           = contents.map;
    $gamePlayer        = contents.player;
};

//-----------------------------------------------------------------------------
// 配置管理器
// ConfigManager
//
// 管理配置数据的静态类。
// The static class that manages the configuration data.

function ConfigManager() {
    throw new Error('This is a static class');
}

ConfigManager.alwaysDash        = false;  // 始终跑步 
ConfigManager.commandRemember   = false;  // 记住指令 

/* BGM 音量 */
Object.defineProperty(ConfigManager, 'bgmVolume', {
    get: function() {
        return AudioManager._bgmVolume;
    },
    set: function(value) {
        AudioManager.bgmVolume = value;
    },
    configurable: true
});

/* BGS 音量 */
Object.defineProperty(ConfigManager, 'bgsVolume', {
    get: function() {
        return AudioManager.bgsVolume;
    },
    set: function(value) {
        AudioManager.bgsVolume = value;
    },
    configurable: true
});

/* ME 音量 */
Object.defineProperty(ConfigManager, 'meVolume', {
    get: function() {
        return AudioManager.meVolume;
    },
    set: function(value) {
        AudioManager.meVolume = value;
    },
    configurable: true
});

/* SE 音量 */
Object.defineProperty(ConfigManager, 'seVolume', {
    get: function() {
        return AudioManager.seVolume;
    },
    set: function(value) {
        AudioManager.seVolume = value;
    },
    configurable: true
});

/* 加载 */
ConfigManager.load = function() {
    var json;
    var config = {};
    try {
        json = StorageManager.load(-1);
    } catch (e) {
        console.error(e);
    }
    if (json) {
        config = JSON.parse(json);
    }
    this.applyData(config);
};

/* 保存 */
ConfigManager.save = function() {
    StorageManager.save(-1, JSON.stringify(this.makeData()));
};

/* 制作数据 */
ConfigManager.makeData = function() {
    var config = {};
    config.alwaysDash = this.alwaysDash;
    config.commandRemember = this.commandRemember;
    config.bgmVolume = this.bgmVolume;
    config.bgsVolume = this.bgsVolume;
    config.meVolume = this.meVolume;
    config.seVolume = this.seVolume;
    return config;
};

/* 执行数据 */
ConfigManager.applyData = function(config) {
    this.alwaysDash = this.readFlag(config, 'alwaysDash');
    this.commandRemember = this.readFlag(config, 'commandRemember');
    this.bgmVolume = this.readVolume(config, 'bgmVolume');
    this.bgsVolume = this.readVolume(config, 'bgsVolume');
    this.meVolume = this.readVolume(config, 'meVolume');
    this.seVolume = this.readVolume(config, 'seVolume');
};

/* 读取标志 */
ConfigManager.readFlag = function(config, name) {
    return !!config[name];
};

/* 读取音量 */
ConfigManager.readVolume = function(config, name) {
    var value = config[name];
    if (value !== undefined) {
        return Number(value).clamp(0, 100);
    } else {
        return 100;
    }
};

//-----------------------------------------------------------------------------
// 存储管理器
// StorageManager
//
// 管理保存游戏数据的存储的静态类。
// The static class that manages storage for saving game data.

function StorageManager() {
    throw new Error('This is a static class');
}

/* 保存 */
StorageManager.save = function(savefileId, json) {
    if (this.isLocalMode()) {
        this.saveToLocalFile(savefileId, json);
    } else {
        this.saveToWebStorage(savefileId, json);
    }
};

/* 加载 */
StorageManager.load = function(savefileId) {
    if (this.isLocalMode()) {
        return this.loadFromLocalFile(savefileId);
    } else {
        return this.loadFromWebStorage(savefileId);
    }
};

/* 是否存在 */
StorageManager.exists = function(savefileId) {
    if (this.isLocalMode()) {
        return this.localFileExists(savefileId);
    } else {
        return this.webStorageExists(savefileId);
    }
};

/* 移除 */
StorageManager.remove = function(savefileId) {
    if (this.isLocalMode()) {
        this.removeLocalFile(savefileId);
    } else {
        this.removeWebStorage(savefileId);
    }
};

/* 备份 */
StorageManager.backup = function(savefileId) {
    if (this.exists(savefileId)) {
        if (this.isLocalMode()) {
            var data = this.loadFromLocalFile(savefileId);
            var compressed = LZString.compressToBase64(data);
            var fs = require('fs');
            var dirPath = this.localFileDirectoryPath();
            var filePath = this.localFilePath(savefileId) + ".bak";
            if (!fs.existsSync(dirPath)) {
                fs.mkdirSync(dirPath);
            }
            fs.writeFileSync(filePath, compressed);
        } else {
            var data = this.loadFromWebStorage(savefileId);
            var compressed = LZString.compressToBase64(data);
            var key = this.webStorageKey(savefileId) + "bak";
            localStorage.setItem(key, compressed);
        }
    }
};

/* 备份是否存在 */
StorageManager.backupExists = function(savefileId) {
    if (this.isLocalMode()) {
        return this.localFileBackupExists(savefileId);
    } else {
        return this.webStorageBackupExists(savefileId);
    }
};

/* 清除备份 */
StorageManager.cleanBackup = function(savefileId) {
	if (this.backupExists(savefileId)) {
		if (this.isLocalMode()) {
			var fs = require('fs');
            var dirPath = this.localFileDirectoryPath();
            var filePath = this.localFilePath(savefileId);
            fs.unlinkSync(filePath + ".bak");
		} else {
		    var key = this.webStorageKey(savefileId);
			localStorage.removeItem(key + "bak");
		}
	}
};

/* 还原备份 */
StorageManager.restoreBackup = function(savefileId) {
    if (this.backupExists(savefileId)) {
        if (this.isLocalMode()) {
            var data = this.loadFromLocalBackupFile(savefileId);
            var compressed = LZString.compressToBase64(data);
            var fs = require('fs');
            var dirPath = this.localFileDirectoryPath();
            var filePath = this.localFilePath(savefileId);
            if (!fs.existsSync(dirPath)) {
                fs.mkdirSync(dirPath);
            }
            fs.writeFileSync(filePath, compressed);
            fs.unlinkSync(filePath + ".bak");
        } else {
            var data = this.loadFromWebStorageBackup(savefileId);
            var compressed = LZString.compressToBase64(data);
            var key = this.webStorageKey(savefileId);
            localStorage.setItem(key, compressed);
            localStorage.removeItem(key + "bak");
        }
    }
};

/* 是否本地模式
 * 在 PC 平台上使用 NW.js，即为本地模式。
 */
StorageManager.isLocalMode = function() {
    return Utils.isNwjs();
};

/* 保存到本地文件 */
StorageManager.saveToLocalFile = function(savefileId, json) {
    var data = LZString.compressToBase64(json);
    var fs = require('fs');
    var dirPath = this.localFileDirectoryPath();
    var filePath = this.localFilePath(savefileId);
    if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath);
    }
    fs.writeFileSync(filePath, data);
};

/* 从本地文件加载 */
StorageManager.loadFromLocalFile = function(savefileId) {
    var data = null;
    var fs = require('fs');
    var filePath = this.localFilePath(savefileId);
    if (fs.existsSync(filePath)) {
        data = fs.readFileSync(filePath, { encoding: 'utf8' });
    }
    return LZString.decompressFromBase64(data);
};

/* 从本地备份文件加载 */
StorageManager.loadFromLocalBackupFile = function(savefileId) {
    var data = null;
    var fs = require('fs');
    var filePath = this.localFilePath(savefileId) + ".bak";
    if (fs.existsSync(filePath)) {
        data = fs.readFileSync(filePath, { encoding: 'utf8' });
    }
    return LZString.decompressFromBase64(data);
};

/* 本地文件备份是否存在 */
StorageManager.localFileBackupExists = function(savefileId) {
    var fs = require('fs');
    return fs.existsSync(this.localFilePath(savefileId) + ".bak");
};

/* 本地文件是否存在 */
StorageManager.localFileExists = function(savefileId) {
    var fs = require('fs');
    return fs.existsSync(this.localFilePath(savefileId));
};

/* 移除本地文件 */
StorageManager.removeLocalFile = function(savefileId) {
    var fs = require('fs');
    var filePath = this.localFilePath(savefileId);
    if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
    }
};

/* 移除浏览器存储 */
StorageManager.saveToWebStorage = function(savefileId, json) {
    var key = this.webStorageKey(savefileId);
    var data = LZString.compressToBase64(json);
    localStorage.setItem(key, data);
};

/* 从浏览器存储加载 */
StorageManager.loadFromWebStorage = function(savefileId) {
    var key = this.webStorageKey(savefileId);
    var data = localStorage.getItem(key);
    return LZString.decompressFromBase64(data);
};

/* 从浏览器存备份储加载 */
StorageManager.loadFromWebStorageBackup = function(savefileId) {
    var key = this.webStorageKey(savefileId) + "bak";
    var data = localStorage.getItem(key);
    return LZString.decompressFromBase64(data);
};

/* 浏览器存储备份是否存在 */
StorageManager.webStorageBackupExists = function(savefileId) {
    var key = this.webStorageKey(savefileId) + "bak";
    return !!localStorage.getItem(key);
};

/* 浏览器存储是否存在 */
StorageManager.webStorageExists = function(savefileId) {
    var key = this.webStorageKey(savefileId);
    return !!localStorage.getItem(key);
};

/* 移除浏览器存储 */
StorageManager.removeWebStorage = function(savefileId) {
    var key = this.webStorageKey(savefileId);
    localStorage.removeItem(key);
};

/* 本地文件目录路径 */
StorageManager.localFileDirectoryPath = function() {
    var path = require('path');

    var base = path.dirname(process.mainModule.filename);
    return path.join(base, 'save/');
};

/* 本地文件路径 */
StorageManager.localFilePath = function(savefileId) {
    var name;
    if (savefileId &lt; 0) {
        name = 'config.rpgsave';
    } else if (savefileId === 0) {
        name = 'global.rpgsave';
    } else {
        name = 'file%1.rpgsave'.format(savefileId);
    }
    return this.localFileDirectoryPath() + name;
};

/* 浏览器存储文键名 */
StorageManager.webStorageKey = function(savefileId) {
    if (savefileId &lt; 0) {
        return 'RPG Config';
    } else if (savefileId === 0) {
        return 'RPG Global';
    } else {
        return 'RPG File%1'.format(savefileId);
    }
};

//-----------------------------------------------------------------------------
// 图像管理器
// ImageManager
//
// 加载图像，创建位图对象和保存它们的静态类。
// The static class that loads images, creates bitmap objects and retains them.

function ImageManager() {
    throw new Error('This is a static class');
}

ImageManager.cache = new CacheMap(ImageManager);  //缓存 

ImageManager._imageCache = new ImageCache();  // 图像缓存 
ImageManager._requestQueue = new RequestQueue();  // 请求队列 
ImageManager._systemReservationId = Utils.generateRuntimeId();  // 系统储存 ID 

/* 生成缓存键名 */
ImageManager._generateCacheKey = function(path, hue){
    return  path + ':' + hue;
};

/* 加载动画 */
ImageManager.loadAnimation = function(filename, hue) {
    return this.loadBitmap('img/animations/', filename, hue, true);
};

/* 加载战斗背景 1 */
ImageManager.loadBattleback1 = function(filename, hue) {
    return this.loadBitmap('img/battlebacks1/', filename, hue, true);
};

/* 加载战斗背景 2 */
ImageManager.loadBattleback2 = function(filename, hue) {
    return this.loadBitmap('img/battlebacks2/', filename, hue, true);
};

/* 加载敌人战斗图（正视图） */
ImageManager.loadEnemy = function(filename, hue) {
    return this.loadBitmap('img/enemies/', filename, hue, true);
};

/* 加载角色行走图 */
ImageManager.loadCharacter = function(filename, hue) {
    return this.loadBitmap('img/characters/', filename, hue, false);
};

/* 加载脸图 */
ImageManager.loadFace = function(filename, hue) {
    return this.loadBitmap('img/faces/', filename, hue, true);
};

/* 加载远景图 */
ImageManager.loadParallax = function(filename, hue) {
    return this.loadBitmap('img/parallaxes/', filename, hue, true);
};

/* 加载图片 */
ImageManager.loadPicture = function(filename, hue) {
    return this.loadBitmap('img/pictures/', filename, hue, true);
};

/* 加载我方战斗图（侧面图） 
 * 在战斗场景的 SideView 战斗系统下使用。
 */
ImageManager.loadSvActor = function(filename, hue) {
    return this.loadBitmap('img/sv_actors/', filename, hue, false);
};

/* 加载敌人战斗图（侧面图） 
 * 在战斗场景的 SideView 战斗系统下使用。
 */
ImageManager.loadSvEnemy = function(filename, hue) {
    return this.loadBitmap('img/sv_enemies/', filename, hue, true);
};

/* 加载系统图片 */
ImageManager.loadSystem = function(filename, hue) {
    return this.loadBitmap('img/system/', filename, hue, false);
};

/* 加载地图图块 */
ImageManager.loadTileset = function(filename, hue) {
    return this.loadBitmap('img/tilesets/', filename, hue, false);
};

/* 加载标题图片 1 */
ImageManager.loadTitle1 = function(filename, hue) {
    return this.loadBitmap('img/titles1/', filename, hue, true);
};

/* 加载标题图片 2 */
ImageManager.loadTitle2 = function(filename, hue) {
    return this.loadBitmap('img/titles2/', filename, hue, true);
};

/* 加载位图 */
ImageManager.loadBitmap = function(folder, filename, hue, smooth) {
    if (filename) {
        var path = folder + encodeURIComponent(filename) + '.png';
        var bitmap = this.loadNormalBitmap(path, hue || 0);
        bitmap.smooth = smooth;
        return bitmap;
    } else {
        return this.loadEmptyBitmap();
    }
};

/* 加载空白位图 */
ImageManager.loadEmptyBitmap = function() {
    var empty = this._imageCache.get('empty');
    if(!empty){
        empty = new Bitmap();
        this._imageCache.add('empty', empty);
        this._imageCache.reserve('empty', empty, this._systemReservationId);
    }

    return empty;
};

/* 加载标准位图 */
ImageManager.loadNormalBitmap = function(path, hue) {
    var key = this._generateCacheKey(path, hue);
    var bitmap = this._imageCache.get(key);
    if (!bitmap) {
        bitmap = Bitmap.load(decodeURIComponent(path));
        bitmap.addLoadListener(function() {
            bitmap.rotateHue(hue);
        });
        this._imageCache.add(key, bitmap);
    }else if(!bitmap.isReady()){
        bitmap.decode();
    }

    return bitmap;
};

/* 清空 */
ImageManager.clear = function() {
    this._imageCache = new ImageCache();
};

/* 是否准备好 */
ImageManager.isReady = function() {
    return this._imageCache.isReady();
};

/* 是否物体的行走图
 * 图片名字!开头（包括!$），取消角色比地图元件高 6 像素的效果以及经
 * 过流体属性图块时的半透明效果。大多用于物件类的角色，如门和宝箱。
 */
ImageManager.isObjectCharacter = function(filename) {
    var sign = filename.match(/^<span class="\!\$">/);
    return sign &amp;&amp; sign[0].contains('!');
};

/* 是否大张的行走图
 * 图片名字$开头（包括!$），该文件就只能容纳一个角色元。
 */
ImageManager.isBigCharacter = function(filename) {
    var sign = filename.match(/^[\!\$]</span>/);
    return sign &amp;&amp; sign[0].contains('$');
};

/* 是否零视差图 
 * 视差图也就是远景图，与地面位移存在视差，零视差相当于地面。 
 * 图片名字!开头，将被视作地面来显示。 
 */
ImageManager.isZeroParallax = function(filename) {
    return filename.charAt(0) === '!';
};

/* 储存动画 */
ImageManager.reserveAnimation = function(filename, hue, reservationId) {
    return this.reserveBitmap('img/animations/', filename, hue, true, reservationId);
};

/* 储存战斗背景1 */
ImageManager.reserveBattleback1 = function(filename, hue, reservationId) {
    return this.reserveBitmap('img/battlebacks1/', filename, hue, true, reservationId);
};

/* 储存战斗背景2 */
ImageManager.reserveBattleback2 = function(filename, hue, reservationId) {
    return this.reserveBitmap('img/battlebacks2/', filename, hue, true, reservationId);
};

/* 储存纵版战斗敌人战斗图 */
ImageManager.reserveEnemy = function(filename, hue, reservationId) {
    return this.reserveBitmap('img/enemies/', filename, hue, true, reservationId);
};

/* 储存角色行走图 */
ImageManager.reserveCharacter = function(filename, hue, reservationId) {
    return this.reserveBitmap('img/characters/', filename, hue, false, reservationId);
};

/* 储存脸图 */
ImageManager.reserveFace = function(filename, hue, reservationId) {
    return this.reserveBitmap('img/faces/', filename, hue, true, reservationId);
};

/* 储存远景图 */
ImageManager.reserveParallax = function(filename, hue, reservationId) {
    return this.reserveBitmap('img/parallaxes/', filename, hue, true, reservationId);
};

/* 储存图片 */
ImageManager.reservePicture = function(filename, hue, reservationId) {
    return this.reserveBitmap('img/pictures/', filename, hue, true, reservationId);
};

/* 储存横版战斗我方战斗图 */
ImageManager.reserveSvActor = function(filename, hue, reservationId) {
    return this.reserveBitmap('img/sv_actors/', filename, hue, false, reservationId);
};

/* 储存横版战斗敌人战斗图 */
ImageManager.reserveSvEnemy = function(filename, hue, reservationId) {
    return this.reserveBitmap('img/sv_enemies/', filename, hue, true, reservationId);
};

/* 储存系统图片 */
ImageManager.reserveSystem = function(filename, hue, reservationId) {
    return this.reserveBitmap('img/system/', filename, hue, false, reservationId || this._systemReservationId);
};

/* 储存地图图块 */
ImageManager.reserveTileset = function(filename, hue, reservationId) {
    return this.reserveBitmap('img/tilesets/', filename, hue, false, reservationId);
};

/* 储存标题图片 1 */
ImageManager.reserveTitle1 = function(filename, hue, reservationId) {
    return this.reserveBitmap('img/titles1/', filename, hue, true, reservationId);
};

/* 储存标题图片 2 */
ImageManager.reserveTitle2 = function(filename, hue, reservationId) {
    return this.reserveBitmap('img/titles2/', filename, hue, true, reservationId);
};

/* 储存位图 */
ImageManager.reserveBitmap = function(folder, filename, hue, smooth, reservationId) {
    if (filename) {
        var path = folder + encodeURIComponent(filename) + '.png';
        var bitmap = this.reserveNormalBitmap(path, hue || 0, reservationId || this._defaultReservationId);
        bitmap.smooth = smooth;
        return bitmap;
    } else {
        return this.loadEmptyBitmap();
    }
};

/* 储存标准位图 */
ImageManager.reserveNormalBitmap = function(path, hue, reservationId){
    var bitmap = this.loadNormalBitmap(path, hue);
    this._imageCache.reserve(this._generateCacheKey(path, hue), bitmap, reservationId);

    return bitmap;
};

/* 释放储存*/
ImageManager.releaseReservation = function(reservationId){
    this._imageCache.releaseReservation(reservationId);
};

/* 设置默认储存 ID*/
ImageManager.setDefaultReservationId = function(reservationId){
    this._defaultReservationId = reservationId;
};

/* 请求动画 */
ImageManager.requestAnimation = function(filename, hue) {
    return this.requestBitmap('img/animations/', filename, hue, true);
};

/* 请求战斗背景 1 */
ImageManager.requestBattleback1 = function(filename, hue) {
    return this.requestBitmap('img/battlebacks1/', filename, hue, true);
};

/* 请求战斗背景 2 */
ImageManager.requestBattleback2 = function(filename, hue) {
    return this.requestBitmap('img/battlebacks2/', filename, hue, true);
};

/* 请求纵版战斗敌人战斗图 */
ImageManager.requestEnemy = function(filename, hue) {
    return this.requestBitmap('img/enemies/', filename, hue, true);
};

/* 请求角色行走图 */
ImageManager.requestCharacter = function(filename, hue) {
    return this.requestBitmap('img/characters/', filename, hue, false);
};

/* 请求脸图 */
ImageManager.requestFace = function(filename, hue) {
    return this.requestBitmap('img/faces/', filename, hue, true);
};

/* 请求远景图 */
ImageManager.requestParallax = function(filename, hue) {
    return this.requestBitmap('img/parallaxes/', filename, hue, true);
};

/* 请求图片 */
ImageManager.requestPicture = function(filename, hue) {
    return this.requestBitmap('img/pictures/', filename, hue, true);
};

/* 请求横版战斗我方战斗图 */
ImageManager.requestSvActor = function(filename, hue) {
    return this.requestBitmap('img/sv_actors/', filename, hue, false);
};

/* 请求横版战斗敌人战斗图 */
ImageManager.requestSvEnemy = function(filename, hue) {
    return this.requestBitmap('img/sv_enemies/', filename, hue, true);
};

/* 请求系统图片 */
ImageManager.requestSystem = function(filename, hue) {
    return this.requestBitmap('img/system/', filename, hue, false);
};

/* 请求地图图块 */
ImageManager.requestTileset = function(filename, hue) {
    return this.requestBitmap('img/tilesets/', filename, hue, false);
};

/* 请求标题图片 1 */
ImageManager.requestTitle1 = function(filename, hue) {
    return this.requestBitmap('img/titles1/', filename, hue, true);
};

/* 请求标题图片 2 */
ImageManager.requestTitle2 = function(filename, hue) {
    return this.requestBitmap('img/titles2/', filename, hue, true);
};

/* 请求位图 */
ImageManager.requestBitmap = function(folder, filename, hue, smooth) {
    if (filename) {
        var path = folder + encodeURIComponent(filename) + '.png';
        var bitmap = this.requestNormalBitmap(path, hue || 0);
        bitmap.smooth = smooth;
        return bitmap;
    } else {
        return this.loadEmptyBitmap();
    }
};

/* 请求标准位图 */
ImageManager.requestNormalBitmap = function(path, hue){
    var key = this._generateCacheKey(path, hue);
    var bitmap = this._imageCache.get(key);
    if(!bitmap){
        bitmap = Bitmap.request(path);
        bitmap.addLoadListener(function(){
            bitmap.rotateHue(hue);
        });
        this._imageCache.add(key, bitmap);
        this._requestQueue.enqueue(key, bitmap);
    }else{
        this._requestQueue.raisePriority(key);
    }

    return bitmap;
};

/* 更新 */
ImageManager.update = function(){
    this._requestQueue.update();
};

/* 清空请求 */
ImageManager.clearRequest = function(){
    this._requestQueue.clear();
};

//-----------------------------------------------------------------------------
// 音频管理器
// AudioManager
//
// 操作 BGM, BGS, ME 和 SE 的静态类。
// The static class that handles BGM, BGS, ME and SE.

function AudioManager() {
    throw new Error('This is a static class');
}

AudioManager._masterVolume   = 1;         // （最小：0，最大：1）(min: 0, max: 1)
AudioManager._bgmVolume      = 100;       // BGM 音量 
AudioManager._bgsVolume      = 100;       // BGS 音量 
AudioManager._meVolume       = 100;       // ME 音量 
AudioManager._seVolume       = 100;       // SE 音量 
AudioManager._currentBgm     = null;      // 当前 BGM 
AudioManager._currentBgs     = null;      // 当前 BGS 
AudioManager._bgmBuffer      = null;      // BGM 缓冲区 
AudioManager._bgsBuffer      = null;      // BGS 缓冲区 
AudioManager._meBuffer       = null;      // ME 缓冲区 
AudioManager._seBuffers      = [];        // SE 缓冲区 
AudioManager._staticBuffers  = [];        // 静态缓冲区 
AudioManager._replayFadeTime = 0.5;       // 重播的淡入时间 
AudioManager._path           = 'audio/';  // 路径 
AudioManager._blobUrl        = null;      // 二进制大对象地址 

/* 主音量 */
Object.defineProperty(AudioManager, 'masterVolume', {
    get: function() {
        return this._masterVolume;
    },
    set: function(value) {
        this._masterVolume = value;
        WebAudio.setMasterVolume(this._masterVolume);
        Graphics.setVideoVolume(this._masterVolume);
    },
    configurable: true
});

/* BGM 音量 */
Object.defineProperty(AudioManager, 'bgmVolume', {
    get: function() {
        return this._bgmVolume;
    },
    set: function(value) {
        this._bgmVolume = value;
        this.updateBgmParameters(this._currentBgm);
    },
    configurable: true
});

/* BGS 音量 */
Object.defineProperty(AudioManager, 'bgsVolume', {
    get: function() {
        return this._bgsVolume;
    },
    set: function(value) {
        this._bgsVolume = value;
        this.updateBgsParameters(this._currentBgs);
    },
    configurable: true
});

/* ME 音量 */
Object.defineProperty(AudioManager, 'meVolume', {
    get: function() {
        return this._meVolume;
    },
    set: function(value) {
        this._meVolume = value;
        this.updateMeParameters(this._currentMe);
    },
    configurable: true
});

/* SE 音量 */
Object.defineProperty(AudioManager, 'seVolume', {
    get: function() {
        return this._seVolume;
    },
    set: function(value) {
        this._seVolume = value;
    },
    configurable: true
});

/* 播放 BGM */
AudioManager.playBgm = function(bgm, pos) {
    if (this.isCurrentBgm(bgm)) {
        this.updateBgmParameters(bgm);
    } else {
        this.stopBgm();
        if (bgm.name) { 
            if(Decrypter.hasEncryptedAudio &amp;&amp; this.shouldUseHtml5Audio()){
                this.playEncryptedBgm(bgm, pos);
            }
            else {
                this._bgmBuffer = this.createBuffer('bgm', bgm.name);
                this.updateBgmParameters(bgm);
                if (!this._meBuffer) {
                    this._bgmBuffer.play(true, pos || 0);
                }
            }
        }
    }
    this.updateCurrentBgm(bgm, pos);
};

/* 播放加密的 BGM */
AudioManager.playEncryptedBgm = function(bgm, pos) {
    var ext = this.audioFileExt();
    var url = this._path + 'bgm/' + encodeURIComponent(bgm.name) + ext;
    url = Decrypter.extToEncryptExt(url);
    Decrypter.decryptHTML5Audio(url, bgm, pos);
};

/* 创建解密的缓冲区 */
AudioManager.createDecryptBuffer = function(url, bgm, pos){
    this._blobUrl = url;
    this._bgmBuffer = this.createBuffer('bgm', bgm.name);
    this.updateBgmParameters(bgm);
    if (!this._meBuffer) {
        this._bgmBuffer.play(true, pos || 0);
    }
    this.updateCurrentBgm(bgm, pos);
};

/* 还原 BGM */
AudioManager.replayBgm = function(bgm) {
    if (this.isCurrentBgm(bgm)) {
        this.updateBgmParameters(bgm);
    } else {
        this.playBgm(bgm, bgm.pos);
        if (this._bgmBuffer) {
            this._bgmBuffer.fadeIn(this._replayFadeTime);
        }
    }
};

/* 是否当前的 BGM */
AudioManager.isCurrentBgm = function(bgm) {
    return (this._currentBgm &amp;&amp; this._bgmBuffer &amp;&amp;
            this._currentBgm.name === bgm.name);
};

/* 更新 BGM 的参数 */
AudioManager.updateBgmParameters = function(bgm) {
    this.updateBufferParameters(this._bgmBuffer, this._bgmVolume, bgm);
};

/* 更新当前的 BGM */
AudioManager.updateCurrentBgm = function(bgm, pos) {
    this._currentBgm = {
        name: bgm.name,      // 名字 
        volume: bgm.volume,  // 音量 
        pitch: bgm.pitch,    // 音调 
        pan: bgm.pan,        // 声像 
        pos: pos             // 缓冲区位置（播放的位置） 
    };
};

/* 停止 BGM */
AudioManager.stopBgm = function() {
    if (this._bgmBuffer) {
        this._bgmBuffer.stop();
        this._bgmBuffer = null;
        this._currentBgm = null;
    }
};

/* 淡出 BGM */
AudioManager.fadeOutBgm = function(duration) {
    if (this._bgmBuffer &amp;&amp; this._currentBgm) {
        this._bgmBuffer.fadeOut(duration);
        this._currentBgm = null;
    }
};

/* 淡入 BGM */
AudioManager.fadeInBgm = function(duration) {
    if (this._bgmBuffer &amp;&amp; this._currentBgm) {
        this._bgmBuffer.fadeIn(duration);
    }
};

/* 播放 BGS */
AudioManager.playBgs = function(bgs, pos) {
    if (this.isCurrentBgs(bgs)) {
        this.updateBgsParameters(bgs);
    } else {
        this.stopBgs();
        if (bgs.name) {
            this._bgsBuffer = this.createBuffer('bgs', bgs.name);
            this.updateBgsParameters(bgs);
            this._bgsBuffer.play(true, pos || 0);
        }
    }
    this.updateCurrentBgs(bgs, pos);
};

/* 还原 BGS */
AudioManager.replayBgs = function(bgs) {
    if (this.isCurrentBgs(bgs)) {
        this.updateBgsParameters(bgs);
    } else {
        this.playBgs(bgs, bgs.pos);
        if (this._bgsBuffer) {
            this._bgsBuffer.fadeIn(this._replayFadeTime);
        }
    }
};

/* 是否当前的 BGS */
AudioManager.isCurrentBgs = function(bgs) {
    return (this._currentBgs &amp;&amp; this._bgsBuffer &amp;&amp;
            this._currentBgs.name === bgs.name);
};

/* 更新 BGS 的参数 */
AudioManager.updateBgsParameters = function(bgs) {
    this.updateBufferParameters(this._bgsBuffer, this._bgsVolume, bgs);
};

/* 更新当前的 BGS */
AudioManager.updateCurrentBgs = function(bgs, pos) {
    this._currentBgs = {
        name: bgs.name,      // 名字 
        volume: bgs.volume,  // 音量
        pitch: bgs.pitch,    // 音调 
        pan: bgs.pan,        // 声像
        pos: pos             // 缓冲区位置（播放的位置） 
    };
};

/* 停止 BGS */
AudioManager.stopBgs = function() {
    if (this._bgsBuffer) {
        this._bgsBuffer.stop();
        this._bgsBuffer = null;
        this._currentBgs = null;
    }
};

/* 淡出 BGS */
AudioManager.fadeOutBgs = function(duration) {
    if (this._bgsBuffer &amp;&amp; this._currentBgs) {
        this._bgsBuffer.fadeOut(duration);
        this._currentBgs = null;
    }
};

/* 淡入 BGS */
AudioManager.fadeInBgs = function(duration) {
    if (this._bgsBuffer &amp;&amp; this._currentBgs) {
        this._bgsBuffer.fadeIn(duration);
    }
};

/* 播放 ME */
AudioManager.playMe = function(me) {
    this.stopMe();
    if (me.name) {
        if (this._bgmBuffer &amp;&amp; this._currentBgm) {
            this._currentBgm.pos = this._bgmBuffer.seek();
            this._bgmBuffer.stop();
        }
        this._meBuffer = this.createBuffer('me', me.name);
        this.updateMeParameters(me);
        this._meBuffer.play(false);
        this._meBuffer.addStopListener(this.stopMe.bind(this));
    }
};

/* 更新 ME 的参数 */
AudioManager.updateMeParameters = function(me) {
    this.updateBufferParameters(this._meBuffer, this._meVolume, me);
};

/* 淡出 ME */
AudioManager.fadeOutMe = function(duration) {
    if (this._meBuffer) {
        this._meBuffer.fadeOut(duration);
    }
};

/* 停止 ME */
AudioManager.stopMe = function() {
    if (this._meBuffer) {
        this._meBuffer.stop();
        this._meBuffer = null;
        if (this._bgmBuffer &amp;&amp; this._currentBgm &amp;&amp; !this._bgmBuffer.isPlaying()) {
            this._bgmBuffer.play(true, this._currentBgm.pos);
            this._bgmBuffer.fadeIn(this._replayFadeTime);
        }
    }
};

/* 播放 SE */
AudioManager.playSe = function(se) {
    if (se.name) {
        this._seBuffers = this._seBuffers.filter(function(audio) {
            return audio.isPlaying();
        });
        var buffer = this.createBuffer('se', se.name);
        this.updateSeParameters(buffer, se);
        buffer.play(false);
        this._seBuffers.push(buffer);
    }
};

/* 更新 SE 的参数 */
AudioManager.updateSeParameters = function(buffer, se) {
    this.updateBufferParameters(buffer, this._seVolume, se);
};

/* 停止 SE */
AudioManager.stopSe = function() {
    this._seBuffers.forEach(function(buffer) {
        buffer.stop();
    });
    this._seBuffers = [];
};

/* 播放静态 SE */
AudioManager.playStaticSe = function(se) {
    if (se.name) {
        this.loadStaticSe(se);
        for (var i = 0; i &lt; this._staticBuffers.length; i) {
            var buffer = this._staticBuffers[i];
            if (buffer._reservedSeName === se.name) {
                buffer.stop();
                this.updateSeParameters(buffer, se);
                buffer.play(false);
                break;
            }
        }
    }
};

/* 加载静态 SE */
AudioManager.loadStaticSe = function(se) {
    if (se.name &amp;&amp; !this.isStaticSe(se)) {
        var buffer = this.createBuffer('se', se.name);
        buffer._reservedSeName = se.name;
        this._staticBuffers.push(buffer);
        if (this.shouldUseHtml5Audio()) {
            Html5Audio.setStaticSe(buffer._url);
        }
    }
};

/* 是否静态 SE */
AudioManager.isStaticSe = function(se) {
    for (var i = 0; i &lt; this._staticBuffers.length; i) {
        var buffer = this._staticBuffers[i];
        if (buffer._reservedSeName === se.name) {
            return true;
        }
    }
    return false;
};

/* 停止所有 */
AudioManager.stopAll = function() {
    this.stopMe();
    this.stopBgm();
    this.stopBgs();
    this.stopSe();
};

/* 保存 BGM */
AudioManager.saveBgm = function() {
    if (this._currentBgm) {
        var bgm = this._currentBgm;
        return {
            name: bgm.name,      // 名字 
            volume: bgm.volume,  // 音量 
            pitch: bgm.pitch,    // 音调 
            pan: bgm.pan,        // 声像
            pos: this._bgmBuffer ? this._bgmBuffer.seek() : 0  // 缓冲区位置（播放的位置） 
        };
    } else {
        return this.makeEmptyAudioObject();
    }
};

/* 保存 BGS */
AudioManager.saveBgs = function() {
    if (this._currentBgs) {
        var bgs = this._currentBgs;
        return {
            name: bgs.name,      // 名字 
            volume: bgs.volume,  // 音量 
            pitch: bgs.pitch,    // 音调 
            pan: bgs.pan,        // 声像 
            pos: this._bgsBuffer ? this._bgsBuffer.seek() : 0  // 缓冲区位置（播放的位置） 
        };
    } else {
        return this.makeEmptyAudioObject();
    }
};

/* 制作空音频对象 */
AudioManager.makeEmptyAudioObject = function() {
    return { name: '', volume: 0, pitch: 0 };
};

/* 创建缓冲区 */
AudioManager.createBuffer = function(folder, name) {
    var ext = this.audioFileExt();
    var url = this._path + folder + '/' + encodeURIComponent(name) + ext;
    if (this.shouldUseHtml5Audio() &amp;&amp; folder === 'bgm') {
        if(this._blobUrl) Html5Audio.setup(this._blobUrl);
        else Html5Audio.setup(url);
        return Html5Audio;
    } else {
        return new WebAudio(url);
    }
};

/* 更新缓冲区参数 */
AudioManager.updateBufferParameters = function(buffer, configVolume, audio) {
    if (buffer &amp;&amp; audio) {
        buffer.volume = configVolume * (audio.volume || 0) / 10000;
        buffer.pitch = (audio.pitch || 0) / 100;
        buffer.pan = (audio.pan || 0) / 100;
    }
};

/* 音频文件扩展名 */
AudioManager.audioFileExt = function() {
    if (WebAudio.canPlayOgg() &amp;&amp; !Utils.isMobileDevice()) {
        return '.ogg';
    } else {
        return '.m4a';
    }
};

/* 是否应该使用 Html5Audio */
AudioManager.shouldUseHtml5Audio = function() {
    // 唯一需要 Html5Audio 的情况是 android/不加密
    // Atsuma-ru 要求强制 WebAudio 也在那里，所以全部只需返回 false 就可以了
    // The only case where we wanted html5audio was android/ no encrypt
    // Atsuma-ru asked to force webaudio there too, so just return false for ALL
    // return Utils.isAndroidChrome() &amp;&amp; !Decrypter.hasEncryptedAudio;
    return false;
};

/* 检测错误 */
AudioManager.checkErrors = function() {
    this.checkWebAudioError(this._bgmBuffer);
    this.checkWebAudioError(this._bgsBuffer);
    this.checkWebAudioError(this._meBuffer);
    this._seBuffers.forEach(function(buffer) {
        this.checkWebAudioError(buffer);
    }.bind(this));
    this._staticBuffers.forEach(function(buffer) {
        this.checkWebAudioError(buffer);
    }.bind(this));
};

/* 检测 WebAudio 错误 */
AudioManager.checkWebAudioError = function(webAudio) {
    if (webAudio &amp;&amp; webAudio.isError()) {
        throw new Error('Failed to load: ' + webAudio.url);
    }
};

//-----------------------------------------------------------------------------
// 声音管理器
// SoundManager
//
// 播放在数据库中定义的音效的静态类。
// The static class that plays sound effects defined in the database.

function SoundManager() {
    throw new Error('This is a static class');
}

/* 预加载重要声音 */
SoundManager.preloadImportantSounds = function() {
    this.loadSystemSound(0);
    this.loadSystemSound(1);
    this.loadSystemSound(2);
    this.loadSystemSound(3);
};

/* 加载系统声音 */
SoundManager.loadSystemSound = function(n) {
    if ($dataSystem) {
        AudioManager.loadStaticSe($dataSystem.sounds[n]);
    }
};

/* 播放系统声音 */
SoundManager.playSystemSound = function(n) {
    if ($dataSystem) {
        AudioManager.playStaticSe($dataSystem.sounds[n]);
    }
};

/* 播放光标音效 */
SoundManager.playCursor = function() {
    this.playSystemSound(0);
};

/* 播放确认音效 */
SoundManager.playOk = function() {
    this.playSystemSound(1);
};

/* 播放取消音效 */
SoundManager.playCancel = function() {
    this.playSystemSound(2);
};

/* 播放蜂鸣器音效 */
SoundManager.playBuzzer = function() {
    this.playSystemSound(3);
};

/* 播放装备音效 */
SoundManager.playEquip = function() {
    this.playSystemSound(4);
};

/* 播放保存音效 */
SoundManager.playSave = function() {
    this.playSystemSound(5);
};

/* 播放加载音效 */
SoundManager.playLoad = function() {
    this.playSystemSound(6);
};

/* 播放战斗开始音效 */
SoundManager.playBattleStart = function() {
    this.playSystemSound(7);
};

/* 播放逃跑音效 */
SoundManager.playEscape = function() {
    this.playSystemSound(8);
};

/* 播放敌人攻击音效 */
SoundManager.playEnemyAttack = function() {
    this.playSystemSound(9);
};

/* 播放敌人受到伤害音效 */
SoundManager.playEnemyDamage = function() {
    this.playSystemSound(10);
};

/* 播放敌人倒下音效 */
SoundManager.playEnemyCollapse = function() {
    this.playSystemSound(11);
};

/* 播放 Boss 倒下音效 1 */
SoundManager.playBossCollapse1 = function() {
    this.playSystemSound(12);
};

/* 播放 Boss 倒下音效 2 */
SoundManager.playBossCollapse2 = function() {
    this.playSystemSound(13);
};

/* 播放角色受到伤害音效 */
SoundManager.playActorDamage = function() {
    this.playSystemSound(14);
};

/* 播放角色倒下音效 */
SoundManager.playActorCollapse = function() {
    this.playSystemSound(15);
};

/* 播放恢复音效音效 */
SoundManager.playRecovery = function() {
    this.playSystemSound(16);
};

/* 播放未击中音效 */
SoundManager.playMiss = function() {
    this.playSystemSound(17);
};

/* 播放闪避音效 */
SoundManager.playEvasion = function() {
    this.playSystemSound(18);
};

/* 播放魔法闪避音效 */
SoundManager.playMagicEvasion = function() {
    this.playSystemSound(19);
};

/* 播放反射音效 */
SoundManager.playReflection = function() {
    this.playSystemSound(20);
};

/* 播放商店音效 */
SoundManager.playShop = function() {
    this.playSystemSound(21);
};

/* 播放使用物品音效 */
SoundManager.playUseItem = function() {
    this.playSystemSound(22);
};

/* 播放使用技能音效 */
SoundManager.playUseSkill = function() {
    this.playSystemSound(23);
};

//-----------------------------------------------------------------------------
// 文本管理器
// TextManager
//
// 操作用语和信息的静态类。
// The static class that handles terms and messages.

function TextManager() {
    throw new Error('This is a static class');
}

/* 基本状态 */
TextManager.basic = function(basicId) {
    return $dataSystem.terms.basic[basicId] || '';
};

/* 能力值 */
TextManager.param = function(paramId) {
    return $dataSystem.terms.params[paramId] || '';
};

/* 指令 */
TextManager.command = function(commandId) {
    return $dataSystem.terms.commands[commandId] || '';
};

/* 信息 */
TextManager.message = function(messageId) {
    return $dataSystem.terms.messages[messageId] || '';
};

/* 获取器 */
TextManager.getter = function(method, param) {
    return {
        get: function() {
            return this[method](param);
        },
        configurable: true
    };
};

/* 货币单位 */
Object.defineProperty(TextManager, 'currencyUnit', {
    get: function() { return $dataSystem.currencyUnit; },
    configurable: true
});

Object.defineProperties(TextManager, {
    level           : TextManager.getter('basic', 0),                     // 等级 
    levelA          : TextManager.getter('basic', 1),                     // 等级（缩写） 
    hp              : TextManager.getter('basic', 2),                     // HP 
    hpA             : TextManager.getter('basic', 3),                     // HP（缩写） 
    mp              : TextManager.getter('basic', 4),                     // MP 
    mpA             : TextManager.getter('basic', 5),                     // MP（缩写） 
    tp              : TextManager.getter('basic', 6),                     // TP 
    tpA             : TextManager.getter('basic', 7),                     // TP（缩写） 
    exp             : TextManager.getter('basic', 8),                     // 经验值 
    expA            : TextManager.getter('basic', 9),                     // 经验值（缩写） 
    fight           : TextManager.getter('command', 0),                   // 战斗 
    escape          : TextManager.getter('command', 1),                   // 逃跑 
    attack          : TextManager.getter('command', 2),                   // 攻击 
    guard           : TextManager.getter('command', 3),                   // 防御 
    item            : TextManager.getter('command', 4),                   // 物品 
    skill           : TextManager.getter('command', 5),                   // 技能 
    equip           : TextManager.getter('command', 6),                   // 装备 
    status          : TextManager.getter('command', 7),                   // 状态 
    formation       : TextManager.getter('command', 8),                   // 整队 
    save            : TextManager.getter('command', 9),                   // 保存 
    gameEnd         : TextManager.getter('command', 10),                  // 游戏结束 
    options         : TextManager.getter('command', 11),                  // 设置 
    weapon          : TextManager.getter('command', 12),                  // 武器 
    armor           : TextManager.getter('command', 13),                  // 护甲 
    keyItem         : TextManager.getter('command', 14),                  // 重要物品 
    equip2          : TextManager.getter('command', 15),                  // 装备 
    optimize        : TextManager.getter('command', 16),                  // 最强装备 
    clear           : TextManager.getter('command', 17),                  // 清空 
    newGame         : TextManager.getter('command', 18),                  // 开始游戏 
    continue_       : TextManager.getter('command', 19),                  // 继续游戏 
    toTitle         : TextManager.getter('command', 21),                  // 回到标题 
    cancel          : TextManager.getter('command', 22),                  // 取消 
    buy             : TextManager.getter('command', 24),                  // 购买 
    sell            : TextManager.getter('command', 25),                  // 出售 
    alwaysDash      : TextManager.getter('message', 'alwaysDash'),        // 始终跑步 
    commandRemember : TextManager.getter('message', 'commandRemember'),   // 记住指令 
    bgmVolume       : TextManager.getter('message', 'bgmVolume'),         // BGM 音量 
    bgsVolume       : TextManager.getter('message', 'bgsVolume'),         // BGS 音量 
    meVolume        : TextManager.getter('message', 'meVolume'),          // ME 音量 
    seVolume        : TextManager.getter('message', 'seVolume'),          // SE 音量 
    possession      : TextManager.getter('message', 'possession'),        // 持有数 
    expTotal        : TextManager.getter('message', 'expTotal'),          // 现在的经验值 
    expNext         : TextManager.getter('message', 'expNext'),           // 距离下一级还有 
    saveMessage     : TextManager.getter('message', 'saveMessage'),       // 存档信息 
    loadMessage     : TextManager.getter('message', 'loadMessage'),       // 读挡信息 
    file            : TextManager.getter('message', 'file'),              // 文件 
    partyName       : TextManager.getter('message', 'partyName'),         // 队伍名 
    emerge          : TextManager.getter('message', 'emerge'),            // 出现 
    preemptive      : TextManager.getter('message', 'preemptive'),        // 先发制人 
    surprise        : TextManager.getter('message', 'surprise'),          // 偷袭 
    escapeStart     : TextManager.getter('message', 'escapeStart'),       // 开始逃跑 
    escapeFailure   : TextManager.getter('message', 'escapeFailure'),     // 逃跑失败 
    victory         : TextManager.getter('message', 'victory'),           // 胜利 
    defeat          : TextManager.getter('message', 'defeat'),            // 战败 
    obtainExp       : TextManager.getter('message', 'obtainExp'),         // 获得经验值 
    obtainGold      : TextManager.getter('message', 'obtainGold'),        // 获得金钱 
    obtainItem      : TextManager.getter('message', 'obtainItem'),        // 获得物品 
    levelUp         : TextManager.getter('message', 'levelUp'),           // 升级 
    obtainSkill     : TextManager.getter('message', 'obtainSkill'),       // 学会技能 
    useItem         : TextManager.getter('message', 'useItem'),           // 使用物品 
    criticalToEnemy : TextManager.getter('message', 'criticalToEnemy'),   // 对敌人暴击 
    criticalToActor : TextManager.getter('message', 'criticalToActor'),   // 对角色暴击 
    actorDamage     : TextManager.getter('message', 'actorDamage'),       // 我方受伤 
    actorRecovery   : TextManager.getter('message', 'actorRecovery'),     // 我方恢复 
    actorGain       : TextManager.getter('message', 'actorGain'),         // 我方点数增加 
    actorLoss       : TextManager.getter('message', 'actorLoss'),         // 我方点数减少 
    actorDrain      : TextManager.getter('message', 'actorDrain'),        // 我方点数吸收 
    actorNoDamage   : TextManager.getter('message', 'actorNoDamage'),     // 我方无伤 
    actorNoHit      : TextManager.getter('message', 'actorNoHit'),        // 没有命中我方 
    enemyDamage     : TextManager.getter('message', 'enemyDamage'),       // 敌人受伤 
    enemyRecovery   : TextManager.getter('message', 'enemyRecovery'),     // 敌人恢复 
    enemyGain       : TextManager.getter('message', 'enemyGain'),         // 敌人点数增加 
    enemyLoss       : TextManager.getter('message', 'enemyLoss'),         // 敌人点数减少 
    enemyDrain      : TextManager.getter('message', 'enemyDrain'),        // 敌人点数吸收 
    enemyNoDamage   : TextManager.getter('message', 'enemyNoDamage'),     // 敌人无伤 
    enemyNoHit      : TextManager.getter('message', 'enemyNoHit'),        // 没有命中敌人 
    evasion         : TextManager.getter('message', 'evasion'),           // 回避 
    magicEvasion    : TextManager.getter('message', 'magicEvasion'),      // 魔法回避 
    magicReflection : TextManager.getter('message', 'magicReflection'),   // 魔法反射 
    counterAttack   : TextManager.getter('message', 'counterAttack'),     // 反击 
    substitute      : TextManager.getter('message', 'substitute'),        // 掩护 
    buffAdd         : TextManager.getter('message', 'buffAdd'),           // 强化 
    debuffAdd       : TextManager.getter('message', 'debuffAdd'),         // 弱化 
    buffRemove      : TextManager.getter('message', 'buffRemove'),        // 解除强化/弱化 
    actionFailure   : TextManager.getter('message', 'actionFailure'),     // 行动失败 
});

//-----------------------------------------------------------------------------
// 场景管理器
// SceneManager
//
// 管理场景切换的静态类。
// The static class that manages scene transitions.

function SceneManager() {
    throw new Error('This is a static class');
}

/*
 * 在 iOS Safari 之外以毫秒为单位获取当前时间。
 * Gets the current time in ms without on iOS Safari.
 * @private
 */
SceneManager._getTimeInMsWithoutMobileSafari = function() {
    return performance.now();
};

SceneManager._scene             = null;   // 当前场景 
SceneManager._nextScene         = null;   // 下一个场景 
SceneManager._stack             = [];     // 栈 
SceneManager._stopped           = false;  // 停止 
SceneManager._sceneStarted      = false;  // 场景开始 
SceneManager._exiting           = false;  // 退出 
SceneManager._previousClass     = null;   // 上一个场景类 
SceneManager._backgroundBitmap  = null;   // 背景位图 
SceneManager._screenWidth       = 816;    // 场景宽 
SceneManager._screenHeight      = 624;    // 场景高 
SceneManager._boxWidth          = 816;    // 盒宽（盒指的 CSS 的盒模型，这里相当于窗口显示区域）
SceneManager._boxHeight         = 624;    // 盒高 
SceneManager._deltaTime = 1.0 / 60.0;     // 增量时间（指多少秒一帧） 
if (!Utils.isMobileSafari()) SceneManager._currentTime = SceneManager._getTimeInMsWithoutMobileSafari();  // 当前时间（毫秒单位的 10 位时间戳）
SceneManager._accumulator = 0.0;          // 累加器（累加时间的）

/* 运行 */
SceneManager.run = function(sceneClass) {
    try {
        this.initialize();
        this.goto(sceneClass);
        this.requestUpdate();
    } catch (e) {
        this.catchException(e);
    }
};

/* 初始化 */
SceneManager.initialize = function() {
    this.initGraphics();
    this.checkFileAccess();
    this.initAudio();
    this.initInput();
    this.initNwjs();
    this.checkPluginErrors();
    this.setupErrorHandlers();
};

/* 初始化图形 */
SceneManager.initGraphics = function() {
    var type = this.preferableRendererType();
    Graphics.initialize(this._screenWidth, this._screenHeight, type);
    Graphics.boxWidth = this._boxWidth;
    Graphics.boxHeight = this._boxHeight;
    Graphics.setLoadingImage('img/system/Loading.png');
    if (Utils.isOptionValid('showfps')) {
        Graphics.showFps();
    }
    if (type === 'webgl') {
        this.checkWebGL();
    }
};

/* 较好的渲染器类型 */
SceneManager.preferableRendererType = function() {
    if (Utils.isOptionValid('canvas')) {
        return 'canvas';
    } else if (Utils.isOptionValid('webgl')) {
        return 'webgl';
    } else {
        return 'auto';
    }
};

/* 是否应该使用 Canvas 渲染 */
SceneManager.shouldUseCanvasRenderer = function() {
    return Utils.isMobileDevice();
};

/* 检测是否支持 WebGL */
SceneManager.checkWebGL = function() {
    if (!Graphics.hasWebGL()) {
        throw new Error('Your browser does not support WebGL.');
    }
};

/* 检测是否拥有文件访问权限 */
SceneManager.checkFileAccess = function() {
    if (!Utils.canReadGameFiles()) {
        throw new Error('Your browser does not allow to read local files.');
    }
};

/* 初始化音频 */
SceneManager.initAudio = function() {
    var noAudio = Utils.isOptionValid('noaudio');
    if (!WebAudio.initialize(noAudio) &amp;&amp; !noAudio) {
        throw new Error('Your browser does not support Web Audio API.');
    }
};

/* 初始化输入 */
SceneManager.initInput = function() {
    Input.initialize();
    TouchInput.initialize();
};

/* 初始化 NW.js */
SceneManager.initNwjs = function() {
    if (Utils.isNwjs()) {
        var gui = require('nw.gui');
        var win = gui.Window.get();
        if (process.platform === 'darwin' &amp;&amp; !win.menu) {
            var menubar = new gui.Menu({ type: 'menubar' });
            var option = { hideEdit: true, hideWindow: true };
            menubar.createMacBuiltin('Game', option);
            win.menu = menubar;
        }
    }
};

/* 检测插件错误 */
SceneManager.checkPluginErrors = function() {
    PluginManager.checkErrors();
};

/* 设置错误处理者 */
SceneManager.setupErrorHandlers = function() {
    window.addEventListener('error', this.onError.bind(this)); // 监听错误事件 
    document.addEventListener('keydown', this.onKeyDown.bind(this));  // 监听按键按下事件 
};

/* 请求更新 */
SceneManager.requestUpdate = function() {
    if (!this._stopped) {
        requestAnimationFrame(this.update.bind(this));
    }
};

/* 更新 */
SceneManager.update = function() {
    try {
        this.tickStart();
        if (Utils.isMobileSafari()) {
            this.updateInputData();
        }
        this.updateManagers();
        this.updateMain();
        this.tickEnd();
    } catch (e) {
        this.catchException(e);
    }
};

/* 结束 */
SceneManager.terminate = function() {
    window.close();
};

/* 当错误 */
SceneManager.onError = function(e) {
    console.error(e.message);
    console.error(e.filename, e.lineno);
    try {
        this.stop();
        Graphics.printError('Error', e.message);
        AudioManager.stopAll();
    } catch (e2) {
    }
};

/* 当按键按下 
 * F5 刷新游戏，F8 显示开发者工具（调试模式下有效） 
 */
SceneManager.onKeyDown = function(event) {
    if (!event.ctrlKey &amp;&amp; !event.altKey) {
        switch (event.keyCode) {
        case 116:   // F5
            if (Utils.isNwjs()) {
                location.reload();
            }
            break;
        case 119:   // F8
            if (Utils.isNwjs() &amp;&amp; Utils.isOptionValid('test')) {
                require('nw.gui').Window.get().showDevTools();
            }
            break;
        }
    }
};

/* 捕捉异常 
 * 终止游戏，并在游戏界面里显示出错误日志。 
 */
SceneManager.catchException = function(e) {
    if (e instanceof Error) {
        Graphics.printError(e.name, e.message);
        console.error(e.stack);
    } else {
        Graphics.printError('UnknownError', e);
    }
    AudioManager.stopAll();
    this.stop();
};

/* tick 开始 
 * tick 为系统的相对时间单位，每执行一次 update 即为一次 tick。 
 */
SceneManager.tickStart = function() {
    Graphics.tickStart();
};

/* tick 结束 */
SceneManager.tickEnd = function() {
    Graphics.tickEnd();
};

/* 更新输入数据 */
SceneManager.updateInputData = function() {
    Input.update();
    TouchInput.update();
};

/* 更新主函数 */
SceneManager.updateMain = function() {
    if (Utils.isMobileSafari()) {
        this.changeScene();
        this.updateScene();
    } else {
        var newTime = this._getTimeInMsWithoutMobileSafari();
        var fTime = (newTime - this._currentTime) / 1000;
        if (fTime &gt; 0.25) fTime = 0.25;
        this._currentTime = newTime;
        this._accumulator += fTime;
        while (this._accumulator &gt;= this._deltaTime) {
            this.updateInputData();
            this.changeScene();
            this.updateScene();
            this._accumulator -= this._deltaTime;
        }
    }
    this.renderScene();
    this.requestUpdate();
};

/* 更新管理器 */
SceneManager.updateManagers = function() {
    ImageManager.update();
};

/* 切换场景 */
SceneManager.changeScene = function() {
    if (this.isSceneChanging() &amp;&amp; !this.isCurrentSceneBusy()) {
        if (this._scene) {
            this._scene.terminate();
            this._scene.detachReservation();
            this._previousClass = this._scene.constructor;
        }
        this._scene = this._nextScene;
        if (this._scene) {
            this._scene.attachReservation();
            this._scene.create();
            this._nextScene = null;
            this._sceneStarted = false;
            this.onSceneCreate();
        }
        if (this._exiting) {
            this.terminate();
        }
    }
};

/* 更新场景 */
SceneManager.updateScene = function() {
    if (this._scene) {
        if (!this._sceneStarted &amp;&amp; this._scene.isReady()) {
            this._scene.start();
            this._sceneStarted = true;
            this.onSceneStart();
        }
        if (this.isCurrentSceneStarted()) {
            this._scene.update();
        }
    }
};

/* 渲染场景 */
SceneManager.renderScene = function() {
    if (this.isCurrentSceneStarted()) {
        Graphics.render(this._scene);
    } else if (this._scene) {
        this.onSceneLoading();
    }
};

/* 当场景创建 */
SceneManager.onSceneCreate = function() {
    Graphics.startLoading();
};

/* 当场景开始 */
SceneManager.onSceneStart = function() {
    Graphics.endLoading();
};

/* 当场景加载中 */
SceneManager.onSceneLoading = function() {
    Graphics.updateLoading();
};

/* 是否场景切换中 */
SceneManager.isSceneChanging = function() {
    return this._exiting || !!this._nextScene;
};

/* 当前场景是否繁忙 */
SceneManager.isCurrentSceneBusy = function() {
    return this._scene &amp;&amp; this._scene.isBusy();
};

/* 当前场景是否开始 */
SceneManager.isCurrentSceneStarted = function() {
    return this._scene &amp;&amp; this._sceneStarted;
};

/* 是否下一个场景 */
SceneManager.isNextScene = function(sceneClass) {
    return this._nextScene &amp;&amp; this._nextScene.constructor === sceneClass;
};

/* 是否上一个场景 */
SceneManager.isPreviousScene = function(sceneClass) {
    return this._previousClass === sceneClass;
};

/* 跳转 */
SceneManager.goto = function(sceneClass) {
    if (sceneClass) {
        this._nextScene = new sceneClass();
    }
    if (this._scene) {
        this._scene.stop();
    }
};

/* 往栈末尾添加元素 */
SceneManager.push = function(sceneClass) {
    this._stack.push(this._scene.constructor);
    this.goto(sceneClass);
};

/* 取出栈末尾的元素 */
SceneManager.pop = function() {
    if (this._stack.length &gt; 0) {
        this.goto(this._stack.pop());
    } else {
        this.exit();
    }
};

/* 退出 */
SceneManager.exit = function() {
    this.goto(null);
    this._exiting = true;
};

/* 清空栈 */
SceneManager.clearStack = function() {
    this._stack = [];
};

/* 停止 */
SceneManager.stop = function() {
    this._stopped = true;
};

/* 准备下一个场景 */
SceneManager.prepareNextScene = function() {
    this._nextScene.prepare.apply(this._nextScene, arguments);
};

/* 快照 
 * 将场景绘制成位图。 
 */
SceneManager.snap = function() {
    return Bitmap.snap(this._scene);
};

/* 快照作为背景
 * 在切换场景的时候将当前场景绘制成图片作为背景。 
 */
SceneManager.snapForBackground = function() {
    this._backgroundBitmap = this.snap();
    this._backgroundBitmap.blur();
};

/* 背景位图 */
SceneManager.backgroundBitmap = function() {
    return this._backgroundBitmap;
};

/* 继续 */
SceneManager.resume = function() {
    this._stopped = false;
    this.requestUpdate();
    if (!Utils.isMobileSafari()) {
        this._currentTime = this._getTimeInMsWithoutMobileSafari();
        this._accumulator = 0;
    }
};

//-----------------------------------------------------------------------------
// 战斗管理器
// BattleManager
//
// 管理战斗进程的静态类。
// The static class that manages battle progress.

function BattleManager() {
    throw new Error('This is a static class');
}

/* 设置
 * @param {Number} troopId 敌群 ID
 * @param {Boolean} canEscape 是否可以逃跑
 * @param {Boolean} canLose 是否可以失败
 */
BattleManager.setup = function(troopId, canEscape, canLose) {
    this.initMembers();
    this._canEscape = canEscape;
    this._canLose = canLose;
    $gameTroop.setup(troopId);
    $gameScreen.onBattleStart();
    this.makeEscapeRatio();
};

/* 初始化成员 */
BattleManager.initMembers = function() {
    this._phase = 'init';              // 阶段 
    this._canEscape = false;           // 可以逃跑 
    this._canLose = false;             // 可以战败 
    this._battleTest = false;          // 战斗测试 
    this._eventCallback = null;        // 事件回调 
    this._preemptive = false;          // 先发制人 
    this._surprise = false;            // 偷袭 
    this._actorIndex = -1;             // 角色索引 
    this._actionForcedBattler = null;  // 强制行动战斗者 
    this._mapBgm = null;               // 地图 BGM 
    this._mapBgs = null;               // 地图 BGS 
    this._actionBattlers = [];         // 行动战斗者 
    this._subject = null;              // 主体 
    this._action = null;               // 行动 
    this._targets = [];                // 目标 
    this._logWindow = null;            // 日志窗口 
    this._statusWindow = null;         // 状态窗口 
    this._spriteset = null;            // 精灵组 
    this._escapeRatio = 0;             // 逃跑概率 
    this._escaped = false;             // 逃跑 
    this._rewards = {};                // 奖励 
    this._turnForced = false;          // 强制回合 
};

/* 是否战斗测试 */
BattleManager.isBattleTest = function() {
    return this._battleTest;
};

/* 设置战斗测试 */
BattleManager.setBattleTest = function(battleTest) {
    this._battleTest = battleTest;
};

/* 设置事件回调 */
BattleManager.setEventCallback = function(callback) {
    this._eventCallback = callback;
};

/* 设置日志窗口 */
BattleManager.setLogWindow = function(logWindow) {
    this._logWindow = logWindow;
};

/* 设置状态窗口 */
BattleManager.setStatusWindow = function(statusWindow) {
    this._statusWindow = statusWindow;
};

/* 设置精灵组 */
BattleManager.setSpriteset = function(spriteset) {
    this._spriteset = spriteset;
};

/* 当遇敌 */
BattleManager.onEncounter = function() {
    this._preemptive = (Math.random() &lt; this.ratePreemptive());
    this._surprise = (Math.random() &lt; this.rateSurprise() &amp;&amp; !this._preemptive);
};

/* 先发制人概率 */
BattleManager.ratePreemptive = function() {
    return $gameParty.ratePreemptive($gameTroop.agility());
};

/* 偷袭概率 */
BattleManager.rateSurprise = function() {
    return $gameParty.rateSurprise($gameTroop.agility());
};

/* 保存 BGM 和 BGS */
BattleManager.saveBgmAndBgs = function() {
    this._mapBgm = AudioManager.saveBgm();
    this._mapBgs = AudioManager.saveBgs();
};

/* 播放战斗 BGM */
BattleManager.playBattleBgm = function() {
    AudioManager.playBgm($gameSystem.battleBgm());
    AudioManager.stopBgs();
};

/* 播放胜利 ME */
BattleManager.playVictoryMe = function() {
    AudioManager.playMe($gameSystem.victoryMe());
};

/* 播放失败 ME */
BattleManager.playDefeatMe = function() {
    AudioManager.playMe($gameSystem.defeatMe());
};

/* 还原战斗 BGM 和 BGS */
BattleManager.replayBgmAndBgs = function() {
    if (this._mapBgm) {
        AudioManager.replayBgm(this._mapBgm);
    } else {
        AudioManager.stopBgm();
    }
    if (this._mapBgs) {
        AudioManager.replayBgs(this._mapBgs);
    }
};

/* 制作逃跑概率 */
BattleManager.makeEscapeRatio = function() {
    this._escapeRatio = 0.5 * $gameParty.agility() / $gameTroop.agility();
};

/* 更新 */
BattleManager.update = function() {
    if (!this.isBusy() &amp;&amp; !this.updateEvent()) {
        switch (this._phase) {
        case 'start': // 开始 
            this.startInput();
            break;
        case 'turn': // 回合
            this.updateTurn();
            break;
        case 'action': // 行动 
            this.updateAction();
            break;
        case 'turnEnd': // 回合结束
            this.updateTurnEnd();
            break;
        case 'battleEnd': // 战斗结束
            this.updateBattleEnd();
            break;
        }
    }
};

/* 更新事件 */
BattleManager.updateEvent = function() {
    switch (this._phase) {
        case 'start': // 开始 
        case 'turn': // 回合 
        case 'turnEnd': // 回合结束
            if (this.isActionForced()) {
                this.processForcedAction();
                return true;
            } else {
                return this.updateEventMain();
            }
    }
    return this.checkAbort();
};

/* 更新事件主函数 */
BattleManager.updateEventMain = function() {
    $gameTroop.updateInterpreter();
    $gameParty.requestMotionRefresh();
    if ($gameTroop.isEventRunning() || this.checkBattleEnd()) {
        return true;
    }
    $gameTroop.setupBattleEvent();
    if ($gameTroop.isEventRunning() || SceneManager.isSceneChanging()) {
        return true;
    }
    return false;
};

/* 是否繁忙 */
BattleManager.isBusy = function() {
    return ($gameMessage.isBusy() || this._spriteset.isBusy() ||
            this._logWindow.isBusy());
};

/* 是否输入中 */
BattleManager.isInputting = function() {
    return this._phase === 'input';
};

/* 是否在回合中 */
BattleManager.isInTurn = function() {
    return this._phase === 'turn';
};

/* 是否回合结束 */
BattleManager.isTurnEnd = function() {
    return this._phase === 'turnEnd';
};

/* 是否终止 */
BattleManager.isAborting = function() {
    return this._phase === 'aborting';
};

/* 是否战斗结束 */
BattleManager.isBattleEnd = function() {
    return this._phase === 'battleEnd';
};

/* 能否逃跑 */
BattleManager.canEscape = function() {
    return this._canEscape;
};

/* 能否失败 */
BattleManager.canLose = function() {
    return this._canLose;
};

/* 是否逃跑 */
BattleManager.isEscaped = function() {
    return this._escaped;
};

/* 角色 */
BattleManager.actor = function() {
    return this._actorIndex &gt;= 0 ? $gameParty.members()[this._actorIndex] : null;
};

/* 清除角色 */
BattleManager.clearActor = function() {
    this.changeActor(-1, '');
};

/* 切换角色 */
BattleManager.changeActor = function(newActorIndex, lastActorActionState) {
    var lastActor = this.actor();
    this._actorIndex = newActorIndex;
    var newActor = this.actor();
    if (lastActor) {
        lastActor.setActionState(lastActorActionState);
    }
    if (newActor) {
        newActor.setActionState('inputting');
    }
};

/* 开始战斗 */
BattleManager.startBattle = function() {
    this._phase = 'start';
    $gameSystem.onBattleStart();
    $gameParty.onBattleStart();
    $gameTroop.onBattleStart();
    this.displayStartMessages();
};

/* 显示开始信息 */
BattleManager.displayStartMessages = function() {
    $gameTroop.enemyNames().forEach(function(name) {
        $gameMessage.add(TextManager.emerge.format(name));
    });
    if (this._preemptive) {
        $gameMessage.add(TextManager.preemptive.format($gameParty.name()));
    } else if (this._surprise) {
        $gameMessage.add(TextManager.surprise.format($gameParty.name()));
    }
};

/* 开始输入 */
BattleManager.startInput = function() {
    this._phase = 'input';
    $gameParty.makeActions();
    $gameTroop.makeActions();
    this.clearActor();
    if (this._surprise || !$gameParty.canInput()) {
        this.startTurn();
    }
};

/* 输入行动 */
BattleManager.inputtingAction = function() {
    return this.actor() ? this.actor().inputtingAction() : null;
};

/* 选择下一个命令 */
BattleManager.selectNextCommand = function() {
    do {
        if (!this.actor() || !this.actor().selectNextCommand()) {
            this.changeActor(this._actorIndex + 1, 'waiting');
            if (this._actorIndex &gt;= $gameParty.size()) {
                this.startTurn();
                break;
            }
        }
    } while (!this.actor().canInput());
};

/* 选择上一个命令 */
BattleManager.selectPreviousCommand = function() {
    do {
        if (!this.actor() || !this.actor().selectPreviousCommand()) {
            this.changeActor(this._actorIndex - 1, 'undecided');
            if (this._actorIndex &lt; 0) {
                return;
            }
        }
    } while (!this.actor().canInput());
};

/* 刷新状态 */
BattleManager.refreshStatus = function() {
    this._statusWindow.refresh();
};

/* 开始回合 */
BattleManager.startTurn = function() {
    this._phase = 'turn';
    this.clearActor();
    $gameTroop.increaseTurn();
    this.makeActionOrders();
    $gameParty.requestMotionRefresh();
    this._logWindow.startTurn();
};

/* 更新回合 */
BattleManager.updateTurn = function() {
    $gameParty.requestMotionRefresh();
    if (!this._subject) {
        this._subject = this.getNextSubject();
    }
    if (this._subject) {
        this.processTurn();
    } else {
        this.endTurn();
    }
};

/* 处理回合 */
BattleManager.processTurn = function() {
    var subject = this._subject;
    var action = subject.currentAction();
    if (action) {
        action.prepare();
        if (action.isValid()) {
            this.startAction();
        }
        subject.removeCurrentAction();
    } else {
        subject.onAllActionsEnd();
        this.refreshStatus();
        this._logWindow.displayAutoAffectedStatus(subject);
        this._logWindow.displayCurrentState(subject);
        this._logWindow.displayRegeneration(subject);
        this._subject = this.getNextSubject();
    }
};

/* 结束回合 */
BattleManager.endTurn = function() {
    this._phase = 'turnEnd';
    this._preemptive = false;
    this._surprise = false;
    this.allBattleMembers().forEach(function(battler) {
        battler.onTurnEnd();
        this.refreshStatus();
        this._logWindow.displayAutoAffectedStatus(battler);
        this._logWindow.displayRegeneration(battler);
    }, this);
    if (this.isForcedTurn()) {
        this._turnForced = false;
    }
};

/* 是否强制回合 */
BattleManager.isForcedTurn = function () {
    return this._turnForced;
};

/* 更新回合结束 */
BattleManager.updateTurnEnd = function() {
    this.startInput();
};

/* 获取下一个主体 */
BattleManager.getNextSubject = function() {
    for (;;) {
        var battler = this._actionBattlers.shift();
        if (!battler) {
            return null;
        }
        if (battler.isBattleMember() &amp;&amp; battler.isAlive()) {
            return battler;
        }
    }
};

/* 所有战斗成员（我方+敌人） */
BattleManager.allBattleMembers = function() {
    return $gameParty.members().concat($gameTroop.members());
};

/* 制作行动次序 */
BattleManager.makeActionOrders = function() {
    var battlers = [];
    if (!this._surprise) {
        battlers = battlers.concat($gameParty.members());
    }
    if (!this._preemptive) {
        battlers = battlers.concat($gameTroop.members());
    }
    battlers.forEach(function(battler) {
        battler.makeSpeed();
    });
    battlers.sort(function(a, b) {
        return b.speed() - a.speed();
    });
    this._actionBattlers = battlers;
};

/* 开始行动 */
BattleManager.startAction = function() {
    var subject = this._subject;
    var action = subject.currentAction();
    var targets = action.makeTargets();
    this._phase = 'action';
    this._action = action;
    this._targets = targets;
    subject.useItem(action.item());
    this._action.applyGlobal();
    this.refreshStatus();
    this._logWindow.startAction(subject, action, targets);
};

/* 更新行动 */
BattleManager.updateAction = function() {
    var target = this._targets.shift();
    if (target) {
        this.invokeAction(this._subject, target);
    } else {
        this.endAction();
    }
};

/* 结束行动 */
BattleManager.endAction = function() {
    this._logWindow.endAction(this._subject);
    this._phase = 'turn';
};

/* 调用行动 */
BattleManager.invokeAction = function(subject, target) {
    this._logWindow.push('pushBaseLine');
    if (Math.random() &lt; this._action.itemCnt(target)) {
        this.invokeCounterAttack(subject, target);
    } else if (Math.random() &lt; this._action.itemMrf(target)) {
        this.invokeMagicReflection(subject, target);
    } else {
        this.invokeNormalAction(subject, target);
    }
    subject.setLastTarget(target);
    this._logWindow.push('popBaseLine');
    this.refreshStatus();
};

/* 调用普通行动 */
BattleManager.invokeNormalAction = function(subject, target) {
    var realTarget = this.applySubstitute(target);
    this._action.apply(realTarget);
    this._logWindow.displayActionResults(subject, realTarget);
};

/* 调用反击 */
BattleManager.invokeCounterAttack = function(subject, target) {
    var action = new Game_Action(target);
    action.setAttack();
    action.apply(subject);
    this._logWindow.displayCounter(target);
    this._logWindow.displayActionResults(target, subject);
};

/* 调用魔法反射 */
BattleManager.invokeMagicReflection = function(subject, target) {
	this._action._reflectionTarget = target;
    this._logWindow.displayReflection(target);
    this._action.apply(subject);
    this._logWindow.displayActionResults(target, subject);
};

/* 应用掩护 */
BattleManager.applySubstitute = function(target) {
    if (this.checkSubstitute(target)) {
        var substitute = target.friendsUnit().substituteBattler();
        if (substitute &amp;&amp; target !== substitute) {
            this._logWindow.displaySubstitute(substitute, target);
            return substitute;
        }
    }
    return target;
};

/* 检测掩护 */
BattleManager.checkSubstitute = function(target) {
    return target.isDying() &amp;&amp; !this._action.isCertainHit();
};

/* 是否强制行动 */
BattleManager.isActionForced = function() {
    return !!this._actionForcedBattler;
};

/* 强制行动 */
BattleManager.forceAction = function(battler) {
    this._actionForcedBattler = battler;
    var index = this._actionBattlers.indexOf(battler);
    if (index &gt;= 0) {
        this._actionBattlers.splice(index, 1);
    }
};

/* 处理强制行动 */
BattleManager.processForcedAction = function() {
    if (this._actionForcedBattler) {
        this._turnForced = true;
        this._subject = this._actionForcedBattler;
        this._actionForcedBattler = null;
        this.startAction();
        this._subject.removeCurrentAction();
    }
};

/* 中止 */
BattleManager.abort = function() {
    this._phase = 'aborting';
};

/* 检测战斗结束 */
BattleManager.checkBattleEnd = function() {
    if (this._phase) {
        if (this.checkAbort()) {
            return true;
        } else if ($gameParty.isAllDead()) {
            this.processDefeat();
            return true;
        } else if ($gameTroop.isAllDead()) {
            this.processVictory();
            return true;
        }
    }
    return false;
};

/* 检测中止 */
BattleManager.checkAbort = function() {
    if ($gameParty.isEmpty() || this.isAborting()) {
        SoundManager.playEscape();
        this._escaped = true;
        this.processAbort();
    }
    return false;
};

/* 处理胜利 */
BattleManager.processVictory = function() {
    $gameParty.removeBattleStates();
    $gameParty.performVictory();
    this.playVictoryMe();
    this.replayBgmAndBgs();
    this.makeRewards();
    this.displayVictoryMessage();
    this.displayRewards();
    this.gainRewards();
    this.endBattle(0);
};

/* 处理逃跑 */
BattleManager.processEscape = function() {
    $gameParty.performEscape();
    SoundManager.playEscape();
    var success = this._preemptive ? true : (Math.random() &lt; this._escapeRatio);
    if (success) {
        this.displayEscapeSuccessMessage();
        this._escaped = true;
        this.processAbort();
    } else {
        this.displayEscapeFailureMessage();
        this._escapeRatio += 0.1;
        $gameParty.clearActions();
        this.startTurn();
    }
    return success;
};

/* 处理中止 */
BattleManager.processAbort = function() {
    $gameParty.removeBattleStates();
    this.replayBgmAndBgs();
    this.endBattle(1);
};

/* 处理战败 */
BattleManager.processDefeat = function() {
    this.displayDefeatMessage();
    this.playDefeatMe();
    if (this._canLose) {
        this.replayBgmAndBgs();
    } else {
        AudioManager.stopBgm();
    }
    this.endBattle(2);
};

/* 结束战斗 */
BattleManager.endBattle = function(result) {
    this._phase = 'battleEnd';
    if (this._eventCallback) {
        this._eventCallback(result);
    }
    if (result === 0) {
        $gameSystem.onBattleWin();
    } else if (this._escaped) {
        $gameSystem.onBattleEscape();
    }
};

/* 更新战斗结束 */
BattleManager.updateBattleEnd = function() {
    if (this.isBattleTest()) {
        AudioManager.stopBgm();
        SceneManager.exit();
    } else if (!this._escaped &amp;&amp; $gameParty.isAllDead()) {
        if (this._canLose) {
            $gameParty.reviveBattleMembers();
            SceneManager.pop();
        } else {
            SceneManager.goto(Scene_Gameover);
        }
    } else {
        SceneManager.pop();
    }
    this._phase = null;
};

/* 制作奖励 */
BattleManager.makeRewards = function() {
    this._rewards = {};
    this._rewards.gold = $gameTroop.goldTotal();
    this._rewards.exp = $gameTroop.expTotal();
    this._rewards.items = $gameTroop.makeDropItems();
};

/* 显示胜利信息 */
BattleManager.displayVictoryMessage = function() {
    $gameMessage.add(TextManager.victory.format($gameParty.name()));
};

/* 显示战败信息 */
BattleManager.displayDefeatMessage = function() {
    $gameMessage.add(TextManager.defeat.format($gameParty.name()));
};

/* 显示逃跑成功信息 */
BattleManager.displayEscapeSuccessMessage = function() {
    $gameMessage.add(TextManager.escapeStart.format($gameParty.name()));
};

/* 显示逃跑失败信息 */
BattleManager.displayEscapeFailureMessage = function() {
    $gameMessage.add(TextManager.escapeStart.format($gameParty.name()));
    $gameMessage.add('\\.' + TextManager.escapeFailure);
};

/* 显示奖励 */
BattleManager.displayRewards = function() {
    this.displayExp();
    this.displayGold();
    this.displayDropItems();
};

/* 显示经验 */
BattleManager.displayExp = function() {
    var exp = this._rewards.exp;
    if (exp &gt; 0) {
        var text = TextManager.obtainExp.format(exp, TextManager.exp);
        $gameMessage.add('\\.' + text);
    }
};

/* 显示金币 */
BattleManager.displayGold = function() {
    var gold = this._rewards.gold;
    if (gold &gt; 0) {
        $gameMessage.add('\\.' + TextManager.obtainGold.format(gold));
    }
};

/* 显示掉落物品 */
BattleManager.displayDropItems = function() {
    var items = this._rewards.items;
    if (items.length &gt; 0) {
        $gameMessage.newPage();
        items.forEach(function(item) {
            $gameMessage.add(TextManager.obtainItem.format(item.name));
        });
    }
};

/* 获得奖励 */
BattleManager.gainRewards = function() {
    this.gainExp();
    this.gainGold();
    this.gainDropItems();
};

/* 获得经验 */
BattleManager.gainExp = function() {
    var exp = this._rewards.exp;
    $gameParty.allMembers().forEach(function(actor) {
        actor.gainExp(exp);
    });
};

/* 获得金币 */
BattleManager.gainGold = function() {
    $gameParty.gainGold(this._rewards.gold);
};

/* 获得掉落物品 */
BattleManager.gainDropItems = function() {
    var items = this._rewards.items;
    items.forEach(function(item) {
        $gameParty.gainItem(item, 1);
    });
};

//-----------------------------------------------------------------------------
// 插件管理器
// PluginManager
//
// 管理插件的静态类。
// The static class that manages the plugins.

function PluginManager() {
    throw new Error('This is a static class');
}

PluginManager._path         = 'js/plugins/';  // 路径 
PluginManager._scripts      = [];             // 脚本 
PluginManager._errorUrls    = [];             // 错误链接 
PluginManager._parameters   = {};             // 参数 

/* 设置 */
PluginManager.setup = function(plugins) {
    plugins.forEach(function(plugin) {
        if (plugin.status &amp;&amp; !this._scripts.contains(plugin.name)) {
            this.setParameters(plugin.name, plugin.parameters);
            this.loadScript(plugin.name + '.js');
            this._scripts.push(plugin.name);
        }
    }, this);
};

/* 检测错误 */
PluginManager.checkErrors = function() {
    var url = this._errorUrls.shift();
    if (url) {
        throw new Error('Failed to load: ' + url);
    }
};

/* 参数 */
PluginManager.parameters = function(name) {
    return this._parameters[name.toLowerCase()] || {};
};

/* 设置参数 */
PluginManager.setParameters = function(name, parameters) {
    this._parameters[name.toLowerCase()] = parameters;
};

/* 加载脚本 */
PluginManager.loadScript = function(name) {
    var url = this._path + name;
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    script.async = false;
    script.onerror = this.onError.bind(this);
    script._url = url;
    document.body.appendChild(script);
};

/* 当错误 */
PluginManager.onError = function(e) {
    this._errorUrls.push(e.target._url);
};</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_对象_rpg_objects_js">对象: rpg_objects.js</h2>
<div class="sectionbody">
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Game_Temp: 游戏_临时</p>
</li>
<li>
<p>Game_System: 游戏_系统</p>
</li>
<li>
<p>Game_Timer: 游戏_计时器</p>
</li>
<li>
<p>Game_Message: 游戏_信息</p>
</li>
<li>
<p>Game_Switches: 游戏_开关</p>
</li>
<li>
<p>Game_Variables: 游戏_变量</p>
</li>
<li>
<p>Game_SelfSwitches: 游戏_独立开关</p>
</li>
<li>
<p>Game_Screen: 游戏_画面</p>
</li>
<li>
<p>Game_Picture: 游戏_图片</p>
</li>
<li>
<p>Game_Item: 游戏_项目</p>
</li>
<li>
<p>Game_Action: 游戏_行动</p>
</li>
<li>
<p>Game_ActionResult: 游戏_行动结果</p>
</li>
<li>
<p>Game_BattlerBase: 游戏_战斗基础</p>
</li>
<li>
<p>Game_Battler: 游戏_战斗者</p>
</li>
<li>
<p>Game_Battler: 游戏_战斗者</p>
</li>
<li>
<p>Game_Actor: 游戏_角色</p>
</li>
<li>
<p>Game_Enemy: 游戏_敌人</p>
</li>
<li>
<p>Game_Actors: 游戏_角色们</p>
</li>
<li>
<p>Game_Unit: 游戏_单位</p>
</li>
<li>
<p>Game_Party: 游戏_队伍</p>
</li>
<li>
<p>Game_Troop: 游戏_敌群</p>
</li>
<li>
<p>Game_Map: 游戏_地图</p>
</li>
<li>
<p>Game_CommonEvent: 游戏_公共事件</p>
</li>
<li>
<p>Game_CharacterBase: 游戏_人物基础</p>
</li>
<li>
<p>Game_Character: 游戏_人物</p>
</li>
<li>
<p>Game_Player: 游戏_玩家</p>
</li>
<li>
<p>Game_Follower: 游戏_跟随者</p>
</li>
<li>
<p>Game_Followers: 游戏_跟随者们</p>
</li>
<li>
<p>Game_Vehicle: 游戏_载具</p>
</li>
<li>
<p>Game_Event: 游戏_事件</p>
</li>
<li>
<p>Game_Interpreter: 游戏_解释器</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-javascript" data-lang="javascript">//=============================================================================
// rpg_objects.js v1.6.1
//=============================================================================

//-----------------------------------------------------------------------------
// 游戏_临时
// Game_Temp
//
// 临时数据（不包含存档数据）的游戏对象类。
// The game object class for temporary data that is not included in save data.

function Game_Temp() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_Temp.prototype.initialize = function() {
    this._isPlaytest = Utils.isOptionValid('test');  // 是否玩家测试 
    this._commonEventId = 0;  // 公共事件 ID 
    this._destinationX = null;  // 目的地 X 坐标 
    this._destinationY = null;  // 目的地 Y 坐标
};

/* 是否玩家测试 */
Game_Temp.prototype.isPlaytest = function() {
    return this._isPlaytest;
};

/* 储存公共事件 */
Game_Temp.prototype.reserveCommonEvent = function(commonEventId) {
    this._commonEventId = commonEventId;
};

/* 清除公共事件 */
Game_Temp.prototype.clearCommonEvent = function() {
    this._commonEventId = 0;
};

/* 是否有公共事件储存 */
Game_Temp.prototype.isCommonEventReserved = function() {
    return this._commonEventId &gt; 0;
};

/* 储存的公共事件 */
Game_Temp.prototype.reservedCommonEvent = function() {
    return $dataCommonEvents[this._commonEventId];
};

/* 设置目的地 */
Game_Temp.prototype.setDestination = function(x, y) {
    this._destinationX = x;
    this._destinationY = y;
};

/* 清除目的地 */
Game_Temp.prototype.clearDestination = function() {
    this._destinationX = null;
    this._destinationY = null;
};

/* 是否目的地有效 */
Game_Temp.prototype.isDestinationValid = function() {
    return this._destinationX !== null;
};

/* 目的地 X 坐标 */
Game_Temp.prototype.destinationX = function() {
    return this._destinationX;
};

/* 目的地 Y 坐标 */
Game_Temp.prototype.destinationY = function() {
    return this._destinationY;
};

//-----------------------------------------------------------------------------
// 游戏_系统
// Game_System
//
// 系统数据的游戏对象类。
// The game object class for the system data.

function Game_System() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_System.prototype.initialize = function() {
    this._saveEnabled = true;  // 保存启用 
    this._menuEnabled = true;  // 菜单启用 
    this._encounterEnabled = true;  // 遇敌启用 
    this._formationEnabled = true;  // 整队启用 
    this._battleCount = 0;  // 战斗次数 
    this._winCount = 0;  // 胜利次数 
    this._escapeCount = 0;  // 逃跑次数 
    this._saveCount = 0;  // 保存次数 
    this._versionId = 0;  // 版本 ID 
    this._framesOnSave = 0;  // 保存时的帧数 
    this._bgmOnSave = null;  // 保存时的 BGM 
    this._bgsOnSave = null;  // 保存时的 BGS 
    this._windowTone = null;  // 窗口色调 
    this._battleBgm = null;  // 战斗 BGM 
    this._victoryMe = null;  // 胜利 ME 
    this._defeatMe = null;  // 战败 ME 
    this._savedBgm = null;  // 保存 BGM 
    this._walkingBgm = null;  // 行走 BGM 
};

/* 是否日文 */
Game_System.prototype.isJapanese = function() {
    return $dataSystem.locale.match(/^ja/);
};

/* 是否中文 */
Game_System.prototype.isChinese = function() {
    return $dataSystem.locale.match(/^zh/);
};

/* 是否韩文 */
Game_System.prototype.isKorean = function() {
    return $dataSystem.locale.match(/^ko/);
};

/* 是否日文/中文/韩文 */
Game_System.prototype.isCJK = function() {
    return $dataSystem.locale.match(/^(ja|zh|ko)/);
};

/* 是否俄文 */
Game_System.prototype.isRussian = function() {
    return $dataSystem.locale.match(/^ru/);
};

/* 是否侧面图 
 * 数据库-系统-选项-使用 SideView 战斗系统 
 */
Game_System.prototype.isSideView = function() {
    return $dataSystem.optSideView;
};

/* 是否存档启用 */
Game_System.prototype.isSaveEnabled = function() {
    return this._saveEnabled;
};

/* 禁用存档 */
Game_System.prototype.disableSave = function() {
    this._saveEnabled = false;
};

/* 启用存档 */
Game_System.prototype.enableSave = function() {
    this._saveEnabled = true;
};

/* 是否菜单启用 */
Game_System.prototype.isMenuEnabled = function() {
    return this._menuEnabled;
};

/* 禁用菜单 */
Game_System.prototype.disableMenu = function() {
    this._menuEnabled = false;
};

/* 启用菜单 */
Game_System.prototype.enableMenu = function() {
    this._menuEnabled = true;
};

/* 是否遇敌启用 */
Game_System.prototype.isEncounterEnabled = function() {
    return this._encounterEnabled;
};

/* 禁用遇敌 */
Game_System.prototype.disableEncounter = function() {
    this._encounterEnabled = false;
};

/* 启用遇敌 */
Game_System.prototype.enableEncounter = function() {
    this._encounterEnabled = true;
};

/* 是否整队启用 */
Game_System.prototype.isFormationEnabled = function() {
    return this._formationEnabled;
};

/* 禁用整队 */
Game_System.prototype.disableFormation = function() {
    this._formationEnabled = false;
};

/* 启用整队 */
Game_System.prototype.enableFormation = function() {
    this._formationEnabled = true;
};

/* 战斗次数 */
Game_System.prototype.battleCount = function() {
    return this._battleCount;
};

/* 胜利次数 */
Game_System.prototype.winCount = function() {
    return this._winCount;
};

/* 逃跑次数 */
Game_System.prototype.escapeCount = function() {
    return this._escapeCount;
};

/* 保存次数 */
Game_System.prototype.saveCount = function() {
    return this._saveCount;
};

/* 版本 ID */
Game_System.prototype.versionId = function() {
    return this._versionId;
};

/* 窗口色调 */
Game_System.prototype.windowTone = function() {
    return this._windowTone || $dataSystem.windowTone;
};

/* 设置窗口色调 */
Game_System.prototype.setWindowTone = function(value) {
    this._windowTone = value;
};

/* 战斗 BGM */
Game_System.prototype.battleBgm = function() {
    return this._battleBgm || $dataSystem.battleBgm;
};

/* 设置战斗 BGM */
Game_System.prototype.setBattleBgm = function(value) {
    this._battleBgm = value;
};

/* 胜利 ME */
Game_System.prototype.victoryMe = function() {
    return this._victoryMe || $dataSystem.victoryMe;
};

/* 设置胜利 ME */
Game_System.prototype.setVictoryMe = function(value) {
    this._victoryMe = value;
};

/* 战败 ME */
Game_System.prototype.defeatMe = function() {
    return this._defeatMe || $dataSystem.defeatMe;
};

/* 设置战败 ME */
Game_System.prototype.setDefeatMe = function(value) {
    this._defeatMe = value;
};

/* 当战斗开始 */
Game_System.prototype.onBattleStart = function() {
    this._battleCount;
};

/* 当战斗胜利 */
Game_System.prototype.onBattleWin = function() {
    this._winCount;
};

/* 当战斗逃跑 */
Game_System.prototype.onBattleEscape = function() {
    this._escapeCount;
};

/* 当保存之前 */
Game_System.prototype.onBeforeSave = function() {
    this._saveCount;
    this._versionId = $dataSystem.versionId;
    this._framesOnSave = Graphics.frameCount;
    this._bgmOnSave = AudioManager.saveBgm();
    this._bgsOnSave = AudioManager.saveBgs();
};

/* 当加载之后 */
Game_System.prototype.onAfterLoad = function() {
    Graphics.frameCount = this._framesOnSave;
    AudioManager.playBgm(this._bgmOnSave);
    AudioManager.playBgs(this._bgsOnSave);
};

/* 游戏时间 */
Game_System.prototype.playtime = function() {
    return Math.floor(Graphics.frameCount / 60);
};

/* 游戏时间文本 */
Game_System.prototype.playtimeText = function() {
    var hour = Math.floor(this.playtime() / 60 / 60);
    var min = Math.floor(this.playtime() / 60) % 60;
    var sec = this.playtime() % 60;
    return hour.padZero(2) + ':' + min.padZero(2) + ':' + sec.padZero(2);
};

/* 保存 BGM */
Game_System.prototype.saveBgm = function() {
    this._savedBgm = AudioManager.saveBgm();
};

/* 还原 BGM */
Game_System.prototype.replayBgm = function() {
    if (this._savedBgm) {
        AudioManager.replayBgm(this._savedBgm);
    }
};

/* 保存行走 BGM 
 * 上载具的时候保存当前的 BGM。
 */
Game_System.prototype.saveWalkingBgm = function() {
    this._walkingBgm = AudioManager.saveBgm();
};

/* 还原行走 BGM */
Game_System.prototype.replayWalkingBgm = function() {
    if (this._walkingBgm) {
        AudioManager.playBgm(this._walkingBgm);
    }
};

/* 保存行走 BGM 2
 * 地图场景刚开始的时候如果在载具中就保存地图的 BGM。 
 */
Game_System.prototype.saveWalkingBgm2 = function() {
	this._walkingBgm = $dataMap.bgm;
};

//-----------------------------------------------------------------------------
// 游戏_计时器
// Game_Timer
//
// 计时器的游戏对象类。 
// The game object class for the timer.

function Game_Timer() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_Timer.prototype.initialize = function() {
    this._frames = 0;
    this._working = false;
};

/* 更新 */
Game_Timer.prototype.update = function(sceneActive) {
    if (sceneActive &amp;&amp; this._working &amp;&amp; this._frames &gt; 0) {
        this._frames--;
        if (this._frames === 0) {
            this.onExpire();
        }
    }
};

/* 开始 */
Game_Timer.prototype.start = function(count) {
    this._frames = count;
    this._working = true;
};

/* 停止 */
Game_Timer.prototype.stop = function() {
    this._working = false;
};

/* 是否工作中 */
Game_Timer.prototype.isWorking = function() {
    return this._working;
};

/* 秒数 */
Game_Timer.prototype.seconds = function() {
    return Math.floor(this._frames / 60);
};

/* 当到期 */
Game_Timer.prototype.onExpire = function() {
    BattleManager.abort();
};

//-----------------------------------------------------------------------------
// 游戏_信息 
// Game_Message
//
// 显示文本或选项等的信息窗口的情况的游戏对象类。
// The game object class for the state of the message window that displays text
// or selections, etc.

function Game_Message() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_Message.prototype.initialize = function() {
    this.clear();
};

/* 清空 */
Game_Message.prototype.clear = function() {
    this._texts = [];  // 文本 
    this._choices = [];  // 选项 
    this._faceName = '';  // 脸图名字 
    this._faceIndex = 0;  // 脸图索引 
    this._background = 0;  // 背景 
    this._positionType = 2;  // 位置类型 
    this._choiceDefaultType = 0;  // 选项默认类型 
    this._choiceCancelType = 0;  // 选项取消类型 
    this._choiceBackground = 0; // 选项背景 
    this._choicePositionType = 2;  // 选项位置类型 
    this._numInputVariableId = 0;  // 数值输入变量 ID 
    this._numInputMaxDigits = 0;  // 数值输入最大位数 
    this._itemChoiceVariableId = 0;  // 物品选择变量 ID 
    this._itemChoiceItypeId = 0;  // 物品选择类型 ID 
    this._scrollMode = false;  // 滚动模式 
    this._scrollSpeed = 2;  // 滚动速度 
    this._scrollNoFast = false;  // 滚动禁止快进 
    this._choiceCallback = null;  // 选择回调 
};

/* 选择 */
Game_Message.prototype.choices = function() {
    return this._choices;
};

/* 脸图名 */
Game_Message.prototype.faceName = function() {
    return this._faceName;
};

/* 脸图索引 */
Game_Message.prototype.faceIndex = function() {
    return this._faceIndex;
};

/* 背景 */
Game_Message.prototype.background = function() {
    return this._background;
};

/* 位置类型 */
Game_Message.prototype.positionType = function() {
    return this._positionType;
};

/* 选项默认类型 */
Game_Message.prototype.choiceDefaultType = function() {
    return this._choiceDefaultType;
};

/* 选项取消类型 */
Game_Message.prototype.choiceCancelType = function() {
    return this._choiceCancelType;
};

/* 选项背景 */
Game_Message.prototype.choiceBackground = function() {
    return this._choiceBackground;
};

/* 选项位置类型 */
Game_Message.prototype.choicePositionType = function() {
    return this._choicePositionType;
};

/* 数值输入变量 ID */
Game_Message.prototype.numInputVariableId = function() {
    return this._numInputVariableId;
};

/* 数值输入最大位数 */
Game_Message.prototype.numInputMaxDigits = function() {
    return this._numInputMaxDigits;
};

/* 物品选择变量 ID */
Game_Message.prototype.itemChoiceVariableId = function() {
    return this._itemChoiceVariableId;
};

/* 物品选择类型 ID */
Game_Message.prototype.itemChoiceItypeId = function() {
    return this._itemChoiceItypeId;
};

/* 滚动模式 */
Game_Message.prototype.scrollMode = function() {
    return this._scrollMode;
};

/* 滚动速度 */
Game_Message.prototype.scrollSpeed = function() {
    return this._scrollSpeed;
};

/* 滚动禁止快进 */
Game_Message.prototype.scrollNoFast = function() {
    return this._scrollNoFast;
};

/* 增加 */
Game_Message.prototype.add = function(text) {
    this._texts.push(text);
};

/* 设置脸图图像 */
Game_Message.prototype.setFaceImage = function(faceName, faceIndex) {
    this._faceName = faceName;
    this._faceIndex = faceIndex;
};

/* 设置背景 */
Game_Message.prototype.setBackground = function(background) {
    this._background = background;
};

/* 设置位置类型 */
Game_Message.prototype.setPositionType = function(positionType) {
    this._positionType = positionType;
};

/* 设置选项 */
Game_Message.prototype.setChoices = function(choices, defaultType, cancelType) {
    this._choices = choices;
    this._choiceDefaultType = defaultType;
    this._choiceCancelType = cancelType;
};

/* 设置选项背景 */
Game_Message.prototype.setChoiceBackground = function(background) {
    this._choiceBackground = background;
};

/* 设置选项位置类型 */
Game_Message.prototype.setChoicePositionType = function(positionType) {
    this._choicePositionType = positionType;
};

/* 设置数值输入 */
Game_Message.prototype.setNumberInput = function(variableId, maxDigits) {
    this._numInputVariableId = variableId;
    this._numInputMaxDigits = maxDigits;
};

/* 设置物品选项 */
Game_Message.prototype.setItemChoice = function(variableId, itemType) {
    this._itemChoiceVariableId = variableId;
    this._itemChoiceItypeId = itemType;
};

/* 设置滚动 */
Game_Message.prototype.setScroll = function(speed, noFast) {
    this._scrollMode = true;
    this._scrollSpeed = speed;
    this._scrollNoFast = noFast;
};

/* 设置选择回调 */
Game_Message.prototype.setChoiceCallback = function(callback) {
    this._choiceCallback = callback;
};

/* 当选择 */
Game_Message.prototype.onChoice = function(n) {
    if (this._choiceCallback) {
        this._choiceCallback(n);
        this._choiceCallback = null;
    }
};

/* 是否有文本 */
Game_Message.prototype.hasText = function() {
    return this._texts.length &gt; 0;
};

/* 是否是选项 */
Game_Message.prototype.isChoice = function() {
    return this._choices.length &gt; 0;
};

/* 是否数值输入 */
Game_Message.prototype.isNumberInput = function() {
    return this._numInputVariableId &gt; 0;
};

/* 是否是物品选择 */
Game_Message.prototype.isItemChoice = function() {
    return this._itemChoiceVariableId &gt; 0;
};

/* 是否繁忙 */
Game_Message.prototype.isBusy = function() {
    return (this.hasText() || this.isChoice() ||
            this.isNumberInput() || this.isItemChoice());
};

/* 新页 */
Game_Message.prototype.newPage = function() {
    if (this._texts.length &gt; 0) {
        this._texts[this._texts.length - 1] = '\f';
    }
};

/* 所有文本 */
Game_Message.prototype.allText = function() {
    return this._texts.join('\n');
};

//-----------------------------------------------------------------------------
// 游戏_开关 
// Game_Switches
//
// 开关的游戏对象类。
// The game object class for switches.

function Game_Switches() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_Switches.prototype.initialize = function() {
    this.clear();
};

/* 清空 */
Game_Switches.prototype.clear = function() {
    this._data = [];
};

/* 值 */
Game_Switches.prototype.value = function(switchId) {
    return !!this._data[switchId];
};

/* 设置值 */
Game_Switches.prototype.setValue = function(switchId, value) {
    if (switchId &gt; 0 &amp;&amp; switchId &lt; $dataSystem.switches.length) {
        this._data[switchId] = value;
        this.onChange();
    }
};

/* 当改变 */
Game_Switches.prototype.onChange = function() {
    $gameMap.requestRefresh();
};

//-----------------------------------------------------------------------------
// 游戏_变量 
// Game_Variables
//
// 变量的游戏对象类。 
// The game object class for variables.

function Game_Variables() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_Variables.prototype.initialize = function() {
    this.clear();
};

/* 清空 */
Game_Variables.prototype.clear = function() {
    this._data = [];
};

/* 值 */
Game_Variables.prototype.value = function(variableId) {
    return this._data[variableId] || 0;
};

/* 设置值 */
Game_Variables.prototype.setValue = function(variableId, value) {
    if (variableId &gt; 0 &amp;&amp; variableId &lt; $dataSystem.variables.length) {
        if (typeof value === 'number') {
            value = Math.floor(value);
        }
        this._data[variableId] = value;
        this.onChange();
    }
};

/* 当改变 */
Game_Variables.prototype.onChange = function() {
    $gameMap.requestRefresh();
};

//-----------------------------------------------------------------------------
// 游戏_独立开关 
// Game_SelfSwitches
//
// 独立开关的游戏对象类。 
// The game object class for self switches.

function Game_SelfSwitches() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_SelfSwitches.prototype.initialize = function() {
    this.clear();
};

/* 清空 */
Game_SelfSwitches.prototype.clear = function() {
    this._data = {};
};

/* 值 */
Game_SelfSwitches.prototype.value = function(key) {
    return !!this._data[key];
};

/* 设置值 */
Game_SelfSwitches.prototype.setValue = function(key, value) {
    if (value) {
        this._data[key] = true;
    } else {
        delete this._data[key];
    }
    this.onChange();
};

/* 当改变 */
Game_SelfSwitches.prototype.onChange = function() {
    $gameMap.requestRefresh();
};

//-----------------------------------------------------------------------------
// 游戏_画面 
// Game_Screen
//
// 画面效果数据（如色调变化和闪烁）的游戏对象类。
// The game object class for screen effect data, such as changes in color tone
// and flashes.

function Game_Screen() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_Screen.prototype.initialize = function() {
    this.clear();
};

/* 清空 */
Game_Screen.prototype.clear = function() {
    this.clearFade();
    this.clearTone();
    this.clearFlash();
    this.clearShake();
    this.clearZoom();
    this.clearWeather();
    this.clearPictures();
};

/* 当战斗开始 */
Game_Screen.prototype.onBattleStart = function() {
    this.clearFade();
    this.clearFlash();
    this.clearShake();
    this.clearZoom();
    this.eraseBattlePictures();
};

/* 亮度 */
Game_Screen.prototype.brightness = function() {
    return this._brightness;
};

/* 色调 */
Game_Screen.prototype.tone = function() {
    return this._tone;
};

/* 闪烁颜色 */
Game_Screen.prototype.flashColor = function() {
    return this._flashColor;
};

/* 震动 */
Game_Screen.prototype.shake = function() {
    return this._shake;
};

/* 缩放 X 坐标 */
Game_Screen.prototype.zoomX = function() {
    return this._zoomX;
};

/* 缩放 Y 坐标 */
Game_Screen.prototype.zoomY = function() {
    return this._zoomY;
};

/* 缩放比例 */
Game_Screen.prototype.zoomScale = function() {
    return this._zoomScale;
};

/* 天气类型 */
Game_Screen.prototype.weatherType = function() {
    return this._weatherType;
};

/* 天气强度 */
Game_Screen.prototype.weatherPower = function() {
    return this._weatherPower;
};

/* 图片 */
Game_Screen.prototype.picture = function(pictureId) {
    var realPictureId = this.realPictureId(pictureId);
    return this._pictures[realPictureId];
};

/* 真正的图片 ID */
Game_Screen.prototype.realPictureId = function(pictureId) {
    if ($gameParty.inBattle()) {
        return pictureId + this.maxPictures();
    } else {
        return pictureId;
    }
};

/* 清除变淡 */
Game_Screen.prototype.clearFade = function() {
    this._brightness = 255;
    this._fadeOutDuration = 0;
    this._fadeInDuration = 0;
};

/* 清除色调 */
Game_Screen.prototype.clearTone = function() {
    this._tone = [0, 0, 0, 0];
    this._toneTarget = [0, 0, 0, 0];
    this._toneDuration = 0;
};

/* 清除闪烁 */
Game_Screen.prototype.clearFlash = function() {
    this._flashColor = [0, 0, 0, 0];
    this._flashDuration = 0;
};

/* 清除震动 */
Game_Screen.prototype.clearShake = function() {
    this._shakePower = 0;
    this._shakeSpeed = 0;
    this._shakeDuration = 0;
    this._shakeDirection = 1;
    this._shake = 0;
};

/* 清除缩放 */
Game_Screen.prototype.clearZoom = function() {
    this._zoomX = 0;
    this._zoomY = 0;
    this._zoomScale = 1;
    this._zoomScaleTarget = 1;
    this._zoomDuration = 0;
};

/* 清除天气 */
Game_Screen.prototype.clearWeather = function() {
    this._weatherType = 'none';
    this._weatherPower = 0;
    this._weatherPowerTarget = 0;
    this._weatherDuration = 0;
};

/* 清除图片 */
Game_Screen.prototype.clearPictures = function() {
    this._pictures = [];
};

/* 消除战斗图片 */
Game_Screen.prototype.eraseBattlePictures = function() {
    this._pictures = this._pictures.slice(0, this.maxPictures() + 1);
};

/* 最大图片数 */
Game_Screen.prototype.maxPictures = function() {
    return 100;
};

/* 开始淡出 */
Game_Screen.prototype.startFadeOut = function(duration) {
    this._fadeOutDuration = duration;
    this._fadeInDuration = 0;
};

/* 开始淡入 */
Game_Screen.prototype.startFadeIn = function(duration) {
    this._fadeInDuration = duration;
    this._fadeOutDuration = 0;
};

/* 开始着色 */
Game_Screen.prototype.startTint = function(tone, duration) {
    this._toneTarget = tone.clone();
    this._toneDuration = duration;
    if (this._toneDuration === 0) {
        this._tone = this._toneTarget.clone();
    }
};

/* 开始闪烁 */
Game_Screen.prototype.startFlash = function(color, duration) {
    this._flashColor = color.clone();
    this._flashDuration = duration;
};

/* 开始震动 */
Game_Screen.prototype.startShake = function(power, speed, duration) {
    this._shakePower = power;
    this._shakeSpeed = speed;
    this._shakeDuration = duration;
};

/* 开始缩放 */
Game_Screen.prototype.startZoom = function(x, y, scale, duration) {
    this._zoomX = x;
    this._zoomY = y;
    this._zoomScaleTarget = scale;
    this._zoomDuration = duration;
};

/* 设置缩放 */
Game_Screen.prototype.setZoom = function(x, y, scale) {
    this._zoomX = x;
    this._zoomY = y;
    this._zoomScale = scale;
};

/* 改变天气 */
Game_Screen.prototype.changeWeather = function(type, power, duration) {
    if (type !== 'none' || duration === 0) {
        this._weatherType = type;
    }
    this._weatherPowerTarget = type === 'none' ? 0 : power;
    this._weatherDuration = duration;
    if (duration === 0) {
        this._weatherPower = this._weatherPowerTarget;
    }
};

/* 更新 */
Game_Screen.prototype.update = function() {
    this.updateFadeOut();
    this.updateFadeIn();
    this.updateTone();
    this.updateFlash();
    this.updateShake();
    this.updateZoom();
    this.updateWeather();
    this.updatePictures();
};

/* 更新淡出 */
Game_Screen.prototype.updateFadeOut = function() {
    if (this._fadeOutDuration &gt; 0) {
        var d = this._fadeOutDuration;
        this._brightness = (this._brightness * (d - 1)) / d;
        this._fadeOutDuration--;
    }
};

/* 更新淡入 */
Game_Screen.prototype.updateFadeIn = function() {
    if (this._fadeInDuration &gt; 0) {
        var d = this._fadeInDuration;
        this._brightness = (this._brightness * (d - 1) + 255) / d;
        this._fadeInDuration--;
    }
};

/* 更新色调 */
Game_Screen.prototype.updateTone = function() {
    if (this._toneDuration &gt; 0) {
        var d = this._toneDuration;
        for (var i = 0; i &lt; 4; i) {
            this._tone[i] = (this._tone[i] * (d - 1) + this._toneTarget[i]) / d;
        }
        this._toneDuration--;
    }
};

/* 更新闪烁 */
Game_Screen.prototype.updateFlash = function() {
    if (this._flashDuration &gt; 0) {
        var d = this._flashDuration;
        this._flashColor[3] *= (d - 1) / d;
        this._flashDuration--;
    }
};

/* 更新震动 */
Game_Screen.prototype.updateShake = function() {
    if (this._shakeDuration &gt; 0 || this._shake !== 0) {
        var delta = (this._shakePower * this._shakeSpeed * this._shakeDirection) / 10;
        if (this._shakeDuration &lt;= 1 &amp;&amp; this._shake * (this._shake + delta) &lt; 0) {
            this._shake = 0;
        } else {
            this._shake += delta;
        }
        if (this._shake &gt; this._shakePower * 2) {
            this._shakeDirection = -1;
        }
        if (this._shake &lt; - this._shakePower * 2) {
            this._shakeDirection = 1;
        }
        this._shakeDuration--;
    }
};

/* 更新缩放 */
Game_Screen.prototype.updateZoom = function() {
    if (this._zoomDuration &gt; 0) {
        var d = this._zoomDuration;
        var t = this._zoomScaleTarget;
        this._zoomScale = (this._zoomScale * (d - 1) + t) / d;
        this._zoomDuration--;
    }
};

/* 更新天气 */
Game_Screen.prototype.updateWeather = function() {
    if (this._weatherDuration &gt; 0) {
        var d = this._weatherDuration;
        var t = this._weatherPowerTarget;
        this._weatherPower = (this._weatherPower * (d - 1) + t) / d;
        this._weatherDuration--;
        if (this._weatherDuration === 0 &amp;&amp; this._weatherPowerTarget === 0) {
            this._weatherType = 'none';
        }
    }
};

/* 更新图片 */
Game_Screen.prototype.updatePictures = function() {
    this._pictures.forEach(function(picture) {
        if (picture) {
            picture.update();
        }
    });
};

/* 开始伤害的闪烁 */
Game_Screen.prototype.startFlashForDamage = function() {
    this.startFlash([255, 0, 0, 128], 8);
};

/* 显示图片 */
Game_Screen.prototype.showPicture = function(pictureId, name, origin, x, y,
                                             scaleX, scaleY, opacity, blendMode) {
    var realPictureId = this.realPictureId(pictureId);
    var picture = new Game_Picture();
    picture.show(name, origin, x, y, scaleX, scaleY, opacity, blendMode);
    this._pictures[realPictureId] = picture;
};

/* 移动图片 */
Game_Screen.prototype.movePicture = function(pictureId, origin, x, y, scaleX,
                                             scaleY, opacity, blendMode, duration) {
    var picture = this.picture(pictureId);
    if (picture) {
        picture.move(origin, x, y, scaleX, scaleY, opacity, blendMode, duration);
    }
};

/* 旋转图片 */
Game_Screen.prototype.rotatePicture = function(pictureId, speed) {
    var picture = this.picture(pictureId);
    if (picture) {
        picture.rotate(speed);
    }
};

/* 着色图片 */
Game_Screen.prototype.tintPicture = function(pictureId, tone, duration) {
    var picture = this.picture(pictureId);
    if (picture) {
        picture.tint(tone, duration);
    }
};

/* 消除图片 */
Game_Screen.prototype.erasePicture = function(pictureId) {
    var realPictureId = this.realPictureId(pictureId);
    this._pictures[realPictureId] = null;
};

//-----------------------------------------------------------------------------
// 游戏_图片 
// Game_Picture
// 
// 图片的游戏对象类。 
// The game object class for a picture.

function Game_Picture() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_Picture.prototype.initialize = function() {
    this.initBasic();
    this.initTarget();
    this.initTone();
    this.initRotation();
};

/* 名字 */
Game_Picture.prototype.name = function() {
    return this._name;
};

/* 原点 */
Game_Picture.prototype.origin = function() {
    return this._origin;
};

/* X 坐标 */
Game_Picture.prototype.x = function() {
    return this._x;
};

/* Y 坐标 */
Game_Picture.prototype.y = function() {
    return this._y;
};

/* X 轴方向的缩放比例 */
Game_Picture.prototype.scaleX = function() {
    return this._scaleX;
};

/* Y 轴方向的缩放比例 */
Game_Picture.prototype.scaleY = function() {
    return this._scaleY;
};

/* 不透明度 */
Game_Picture.prototype.opacity = function() {
    return this._opacity;
};

/* 混合模式 */
Game_Picture.prototype.blendMode = function() {
    return this._blendMode;
};

/* 色调 */
Game_Picture.prototype.tone = function() {
    return this._tone;
};

/* 角度 */
Game_Picture.prototype.angle = function() {
    return this._angle;
};

/* 初始化基本参数 */
Game_Picture.prototype.initBasic = function() {
    this._name = '';
    this._origin = 0;
    this._x = 0;
    this._y = 0;
    this._scaleX = 100;
    this._scaleY = 100;
    this._opacity = 255;
    this._blendMode = 0;
};

/* 初始化目标 */
Game_Picture.prototype.initTarget = function() {
    this._targetX = this._x;
    this._targetY = this._y;
    this._targetScaleX = this._scaleX;
    this._targetScaleY = this._scaleY;
    this._targetOpacity = this._opacity;
    this._duration = 0;
};

/* 初始化色调 */
Game_Picture.prototype.initTone = function() {
    this._tone = null;
    this._toneTarget = null;
    this._toneDuration = 0;
};

/* 初始化旋转 */
Game_Picture.prototype.initRotation = function() {
    this._angle = 0;
    this._rotationSpeed = 0;
};

/* 显示 */
Game_Picture.prototype.show = function(name, origin, x, y, scaleX,
                                       scaleY, opacity, blendMode) {
    this._name = name;
    this._origin = origin;
    this._x = x;
    this._y = y;
    this._scaleX = scaleX;
    this._scaleY = scaleY;
    this._opacity = opacity;
    this._blendMode = blendMode;
    this.initTarget();
    this.initTone();
    this.initRotation();
};

/* 移动 */
Game_Picture.prototype.move = function(origin, x, y, scaleX, scaleY,
                                       opacity, blendMode, duration) {
    this._origin = origin;
    this._targetX = x;
    this._targetY = y;
    this._targetScaleX = scaleX;
    this._targetScaleY = scaleY;
    this._targetOpacity = opacity;
    this._blendMode = blendMode;
    this._duration = duration;
};

/* 旋转 */
Game_Picture.prototype.rotate = function(speed) {
    this._rotationSpeed = speed;
};

/* 着色 */
Game_Picture.prototype.tint = function(tone, duration) {
    if (!this._tone) {
        this._tone = [0, 0, 0, 0];
    }
    this._toneTarget = tone.clone();
    this._toneDuration = duration;
    if (this._toneDuration === 0) {
        this._tone = this._toneTarget.clone();
    }
};

/* 消除 */
Game_Picture.prototype.erase = function() {
    this._name = '';
    this._origin = 0;
    this.initTarget();
    this.initTone();
    this.initRotation();
};

/* 更新 */
Game_Picture.prototype.update = function() {
    this.updateMove();
    this.updateTone();
    this.updateRotation();
};

/* 更新移动 */
Game_Picture.prototype.updateMove = function() {
    if (this._duration &gt; 0) {
        var d = this._duration;
        this._x = (this._x * (d - 1) + this._targetX) / d;
        this._y = (this._y * (d - 1) + this._targetY) / d;
        this._scaleX  = (this._scaleX  * (d - 1) + this._targetScaleX)  / d;
        this._scaleY  = (this._scaleY  * (d - 1) + this._targetScaleY)  / d;
        this._opacity = (this._opacity * (d - 1) + this._targetOpacity) / d;
        this._duration--;
    }
};

/* 更新色调 */
Game_Picture.prototype.updateTone = function() {
    if (this._toneDuration &gt; 0) {
        var d = this._toneDuration;
        for (var i = 0; i &lt; 4; i) {
            this._tone[i] = (this._tone[i] * (d - 1) + this._toneTarget[i]) / d;
        }
        this._toneDuration--;
    }
};

/* 更新旋转 */
Game_Picture.prototype.updateRotation = function() {
    if (this._rotationSpeed !== 0) {
        this._angle += this._rotationSpeed / 2;
    }
};

//-----------------------------------------------------------------------------
// 游戏_项目
// Game_Item
// 
// 处理技能、物品、武器和护甲的游戏对象类。这是必须的，因为保存数据不应包含数据库对象本身。
// The game object class for handling skills, items, weapons, and armor. It is
// required because save data should not include the database object itself.
// 
// PS：Item 指代很多，翻译的时候把仅包含物品（Item）、武器和护甲的 Item 称为物品（有
// 的 Item 不含武器和护甲），包含技能或者其他（如指令窗口的选项）的 Item 翻译为项目。 

function Game_Item() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_Item.prototype.initialize = function(item) {
    this._dataClass = '';
    this._itemId = 0;
    if (item) {
        this.setObject(item);
    }
};

/* 是否是技能 */
Game_Item.prototype.isSkill = function() {
    return this._dataClass === 'skill';
};

/* 是否是物品 */
Game_Item.prototype.isItem = function() {
    return this._dataClass === 'item';
};

/* 是否是可使用的项目 */
Game_Item.prototype.isUsableItem = function() {
    return this.isSkill() || this.isItem();
};

/* 是否是武器 */
Game_Item.prototype.isWeapon = function() {
    return this._dataClass === 'weapon';
};

/* 是否是护甲 */
Game_Item.prototype.isArmor = function() {
    return this._dataClass === 'armor';
};

/* 是否是可装备的项目 */
Game_Item.prototype.isEquipItem = function() {
    return this.isWeapon() || this.isArmor();
};

/* 是否为空 */
Game_Item.prototype.isNull = function() {
    return this._dataClass === '';
};

/* 项目 ID */
Game_Item.prototype.itemId = function() {
    return this._itemId;
};

/* 对象 */
Game_Item.prototype.object = function() {
    if (this.isSkill()) {
        return $dataSkills[this._itemId];
    } else if (this.isItem()) {
        return $dataItems[this._itemId];
    } else if (this.isWeapon()) {
        return $dataWeapons[this._itemId];
    } else if (this.isArmor()) {
        return $dataArmors[this._itemId];
    } else {
        return null;
    }
};

/* 设置对象 */
Game_Item.prototype.setObject = function(item) {
    if (DataManager.isSkill(item)) {
        this._dataClass = 'skill';
    } else if (DataManager.isItem(item)) {
        this._dataClass = 'item';
    } else if (DataManager.isWeapon(item)) {
        this._dataClass = 'weapon';
    } else if (DataManager.isArmor(item)) {
        this._dataClass = 'armor';
    } else {
        this._dataClass = '';
    }
    this._itemId = item ? item.id : 0;
};

/* 设置装备 */
Game_Item.prototype.setEquip = function(isWeapon, itemId) {
    this._dataClass = isWeapon ? 'weapon' : 'armor';
    this._itemId = itemId;
};

//-----------------------------------------------------------------------------
// 游戏_行动 
// Game_Action
//
// 战斗行动的游戏对象类。 
// The game object class for a battle action.

function Game_Action() {
    this.initialize.apply(this, arguments);
}


Game_Action.EFFECT_RECOVER_HP       = 11;  // 效果-恢复 HP 
Game_Action.EFFECT_RECOVER_MP       = 12;  // 效果-恢复 MP 
Game_Action.EFFECT_GAIN_TP          = 13;  // 效果-获得 TP 
Game_Action.EFFECT_ADD_STATE        = 21;  // 效果-附加状态 
Game_Action.EFFECT_REMOVE_STATE     = 22;  // 效果-解除状态 
Game_Action.EFFECT_ADD_BUFF         = 31;  // 效果-强化 
Game_Action.EFFECT_ADD_DEBUFF       = 32;  // 效果-弱化 
Game_Action.EFFECT_REMOVE_BUFF      = 33;  // 效果-解除强化 
Game_Action.EFFECT_REMOVE_DEBUFF    = 34;  // 效果-解除弱化 
Game_Action.EFFECT_SPECIAL          = 41;  // 效果-特殊效果 
Game_Action.EFFECT_GROW             = 42;  // 效果-成长 
Game_Action.EFFECT_LEARN_SKILL      = 43;  // 效果-学会技能 
Game_Action.EFFECT_COMMON_EVENT     = 44;  // 效果-公共事件 
Game_Action.SPECIAL_EFFECT_ESCAPE   = 0;   // 特殊效果-逃跑 
Game_Action.HITTYPE_CERTAIN         = 0;   // 命中类型-必定命中 
Game_Action.HITTYPE_PHYSICAL        = 1;   // 命中类型-物理攻击 
Game_Action.HITTYPE_MAGICAL         = 2;   // 命中类型-魔法攻击 

/* 初始化 */
Game_Action.prototype.initialize = function(subject, forcing) {
    this._subjectActorId = 0;
    this._subjectEnemyIndex = -1;
    this._forcing = forcing || false;
    this.setSubject(subject);
    this.clear();
};

/* 清除 */
Game_Action.prototype.clear = function() {
    this._item = new Game_Item();
    this._targetIndex = -1;
};

/* 设置主体 */
Game_Action.prototype.setSubject = function(subject) {
    if (subject.isActor()) {
        this._subjectActorId = subject.actorId();
        this._subjectEnemyIndex = -1;
    } else {
        this._subjectEnemyIndex = subject.index();
        this._subjectActorId = 0;
    }
};

/* 主体 */
Game_Action.prototype.subject = function() {
    if (this._subjectActorId &gt; 0) {
        return $gameActors.actor(this._subjectActorId);
    } else {
        return $gameTroop.members()[this._subjectEnemyIndex];
    }
};

/* 我方单位 */
Game_Action.prototype.friendsUnit = function() {
    return this.subject().friendsUnit();
};

/* 敌方单位 */
Game_Action.prototype.opponentsUnit = function() {
    return this.subject().opponentsUnit();
};

/* 设置敌人行动 */
Game_Action.prototype.setEnemyAction = function(action) {
    if (action) {
        this.setSkill(action.skillId);
    } else {
        this.clear();
    }
};

/* 设置普通攻击 */
Game_Action.prototype.setAttack = function() {
    this.setSkill(this.subject().attackSkillId());
};

/* 设置防御 */
Game_Action.prototype.setGuard = function() {
    this.setSkill(this.subject().guardSkillId());
};

/* 设置技能 */
Game_Action.prototype.setSkill = function(skillId) {
    this._item.setObject($dataSkills[skillId]);
};

/* 设置物品 */
Game_Action.prototype.setItem = function(itemId) {
    this._item.setObject($dataItems[itemId]);
};

/* 设置项目对象 */
Game_Action.prototype.setItemObject = function(object) {
    this._item.setObject(object);
};

/* 设置目标 */
Game_Action.prototype.setTarget = function(targetIndex) {
    this._targetIndex = targetIndex;
};

/* 项目 */
Game_Action.prototype.item = function() {
    return this._item.object();
};

/* 是否是技能 */
Game_Action.prototype.isSkill = function() {
    return this._item.isSkill();
};

/* 是否是物品 */
Game_Action.prototype.isItem = function() {
    return this._item.isItem();
};

/* 连续次数 */
Game_Action.prototype.numRepeats = function() {
    var repeats = this.item().repeats;
    if (this.isAttack()) {
        repeats += this.subject().attackTimesAdd();
    }
    return Math.floor(repeats);
};

/* 检测项目范围 */
Game_Action.prototype.checkItemScope = function(list) {
    return list.contains(this.item().scope);
};

/* 是否是作用于敌方 */
Game_Action.prototype.isForOpponent = function() {
    return this.checkItemScope([1, 2, 3, 4, 5, 6]);
};

/* 是否是作用于我方 */
Game_Action.prototype.isForFriend = function() {
    return this.checkItemScope([7, 8, 9, 10, 11]);
};

/* 是否作用于我方无法战斗的 */
Game_Action.prototype.isForDeadFriend = function() {
    return this.checkItemScope([9, 10]);
};

/* 是否作用于使用者 */
Game_Action.prototype.isForUser = function() {
    return this.checkItemScope([11]);
};

/* 是否作用于单体 */
Game_Action.prototype.isForOne = function() {
    return this.checkItemScope([1, 3, 7, 9, 11]);
};

/* 是否作用于随机 */
Game_Action.prototype.isForRandom = function() {
    return this.checkItemScope([3, 4, 5, 6]);
};

/* 是否作用于全体 */
Game_Action.prototype.isForAll = function() {
    return this.checkItemScope([2, 8, 10]);
};

/* 是否需要选择 */
Game_Action.prototype.needsSelection = function() {
    return this.checkItemScope([1, 7, 9]);
};

/* 目标数量 */
Game_Action.prototype.numTargets = function() {
    return this.isForRandom() ? this.item().scope - 2 : 0;
};

/* 检测伤害类型 */
Game_Action.prototype.checkDamageType = function(list) {
    return list.contains(this.item().damage.type);
};

/* 是否是 HP 效果 */
Game_Action.prototype.isHpEffect = function() {
    return this.checkDamageType([1, 3, 5]);
};

/* 是否是 MP 效果 */
Game_Action.prototype.isMpEffect = function() {
    return this.checkDamageType([2, 4, 6]);
};

/* 是否是伤害 */
Game_Action.prototype.isDamage = function() {
    return this.checkDamageType([1, 2]);
};

/* 是否是恢复 */
Game_Action.prototype.isRecover = function() {
    return this.checkDamageType([3, 4]);
};

/* 是否是吸收 */
Game_Action.prototype.isDrain = function() {
    return this.checkDamageType([5, 6]);
};

/* 是否是 HP 恢复 */
Game_Action.prototype.isHpRecover = function() {
    return this.checkDamageType([3]);
};

/* 是否是 MP 恢复 */
Game_Action.prototype.isMpRecover = function() {
    return this.checkDamageType([4]);
};

/* 是否是必定命中 */
Game_Action.prototype.isCertainHit = function() {
    return this.item().hitType === Game_Action.HITTYPE_CERTAIN;
};

/* 是否是物理攻击 */
Game_Action.prototype.isPhysical = function() {
    return this.item().hitType === Game_Action.HITTYPE_PHYSICAL;
};

/* 是否是魔法攻击 */
Game_Action.prototype.isMagical = function() {
    return this.item().hitType === Game_Action.HITTYPE_MAGICAL;
};

/* 是否是普通攻击 */
Game_Action.prototype.isAttack = function() {
    return this.item() === $dataSkills[this.subject().attackSkillId()];
};

/* 是否是防御 */
Game_Action.prototype.isGuard = function() {
    return this.item() === $dataSkills[this.subject().guardSkillId()];
};

/* 是否是魔法技能 */
Game_Action.prototype.isMagicSkill = function() {
    if (this.isSkill()) {
        return $dataSystem.magicSkills.contains(this.item().stypeId);
    } else {
        return false;
    }
};

/* 决定随机目标 */
Game_Action.prototype.decideRandomTarget = function() {
    var target;
    if (this.isForDeadFriend()) {
        target = this.friendsUnit().randomDeadTarget();
    } else if (this.isForFriend()) {
        target = this.friendsUnit().randomTarget();
    } else {
        target = this.opponentsUnit().randomTarget();
    }
    if (target) {
        this._targetIndex = target.index();
    } else {
        this.clear();
    }
};

/* 设置混乱 */
Game_Action.prototype.setConfusion = function() {
    this.setAttack();
};

/* 准备 */
Game_Action.prototype.prepare = function() {
    if (this.subject().isConfused() &amp;&amp; !this._forcing) {
        this.setConfusion();
    }
};

/* 是否有效 */
Game_Action.prototype.isValid = function() {
    return (this._forcing &amp;&amp; this.item()) || this.subject().canUse(this.item());
};

/* 速度 */
Game_Action.prototype.speed = function() {
    var agi = this.subject().agi;
    var speed = agi + Math.randomInt(Math.floor(5 + agi / 4));
    if (this.item()) {
        speed += this.item().speed;
    }
    if (this.isAttack()) {
        speed += this.subject().attackSpeed();
    }
    return speed;
};

/* 制作目标 */
Game_Action.prototype.makeTargets = function() {
    var targets = [];
    if (!this._forcing &amp;&amp; this.subject().isConfused()) {
        targets = [this.confusionTarget()];
    } else if (this.isForOpponent()) {
        targets = this.targetsForOpponents();
    } else if (this.isForFriend()) {
        targets = this.targetsForFriends();
    }
    return this.repeatTargets(targets);
};

/* 连续目标 */
Game_Action.prototype.repeatTargets = function(targets) {
    var repeatedTargets = [];
    var repeats = this.numRepeats();
    for (var i = 0; i &lt; targets.length; i) {
        var target = targets[i];
        if (target) {
            for (var j = 0; j &lt; repeats; j) {
                repeatedTargets.push(target);
            }
        }
    }
    return repeatedTargets;
};

/* 混乱目标 */
Game_Action.prototype.confusionTarget = function() {
    switch (this.subject().confusionLevel()) {
    case 1:
        return this.opponentsUnit().randomTarget();
    case 2:
        if (Math.randomInt(2) === 0) {
            return this.opponentsUnit().randomTarget();
        }
        return this.friendsUnit().randomTarget();
    default:
        return this.friendsUnit().randomTarget();
    }
};

/* 敌方目标 */
Game_Action.prototype.targetsForOpponents = function() {
    var targets = [];
    var unit = this.opponentsUnit();
    if (this.isForRandom()) {
        for (var i = 0; i &lt; this.numTargets(); i) {
            targets.push(unit.randomTarget());
        }
    } else if (this.isForOne()) {
        if (this._targetIndex &lt; 0) {
            targets.push(unit.randomTarget());
        } else {
            targets.push(unit.smoothTarget(this._targetIndex));
        }
    } else {
        targets = unit.aliveMembers();
    }
    return targets;
};

/* 我方目标 */
Game_Action.prototype.targetsForFriends = function() {
    var targets = [];
    var unit = this.friendsUnit();
    if (this.isForUser()) {
        return [this.subject()];
    } else if (this.isForDeadFriend()) {
        if (this.isForOne()) {
            targets.push(unit.smoothDeadTarget(this._targetIndex));
        } else {
            targets = unit.deadMembers();
        }
    } else if (this.isForOne()) {
        if (this._targetIndex &lt; 0) {
            targets.push(unit.randomTarget());
        } else {
            targets.push(unit.smoothTarget(this._targetIndex));
        }
    } else {
        targets = unit.aliveMembers();
    }
    return targets;
};

/* 求值 */
Game_Action.prototype.evaluate = function() {
    var value = 0;
    this.itemTargetCandidates().forEach(function(target) {
        var targetValue = this.evaluateWithTarget(target);
        if (this.isForAll()) {
            value += targetValue;
        } else if (targetValue &gt; value) {
            value = targetValue;
            this._targetIndex = target.index();
        }
    }, this);
    value *= this.numRepeats();
    if (value &gt; 0) {
        value += Math.random();
    }
    return value;
};

/* 候选项目目标 */
Game_Action.prototype.itemTargetCandidates = function() {
    if (!this.isValid()) {
        return [];
    } else if (this.isForOpponent()) {
        return this.opponentsUnit().aliveMembers();
    } else if (this.isForUser()) {
        return [this.subject()];
    } else if (this.isForDeadFriend()) {
        return this.friendsUnit().deadMembers();
    } else {
        return this.friendsUnit().aliveMembers();
    }
};

/* 对目标求值 */
Game_Action.prototype.evaluateWithTarget = function(target) {
    if (this.isHpEffect()) {
        var value = this.makeDamageValue(target, false);
        if (this.isForOpponent()) {
            return value / Math.max(target.hp, 1);
        } else {
            var recovery = Math.min(-value, target.mhp - target.hp);
            return recovery / target.mhp;
        }
    }
};

/* 检验执行 */
Game_Action.prototype.testApply = function(target) {
    return (this.isForDeadFriend() === target.isDead() &amp;&amp;
            ($gameParty.inBattle() || this.isForOpponent() ||
            (this.isHpRecover() &amp;&amp; target.hp &lt; target.mhp) ||
            (this.isMpRecover() &amp;&amp; target.mp &lt; target.mmp) ||
            (this.hasItemAnyValidEffects(target))));
};

/* 项目是否有任何有效的效果 */
Game_Action.prototype.hasItemAnyValidEffects = function(target) {
    return this.item().effects.some(function(effect) {
        return this.testItemEffect(target, effect);
    }, this);
};

/* 检验项目效果 */
Game_Action.prototype.testItemEffect = function(target, effect) {
    switch (effect.code) {
    case Game_Action.EFFECT_RECOVER_HP:
        return target.hp &lt; target.mhp || effect.value1 &lt; 0 || effect.value2 &lt; 0;
    case Game_Action.EFFECT_RECOVER_MP:
        return target.mp &lt; target.mmp || effect.value1 &lt; 0 || effect.value2 &lt; 0;
    case Game_Action.EFFECT_ADD_STATE:
        return !target.isStateAffected(effect.dataId);
    case Game_Action.EFFECT_REMOVE_STATE:
        return target.isStateAffected(effect.dataId);
    case Game_Action.EFFECT_ADD_BUFF:
        return !target.isMaxBuffAffected(effect.dataId);
    case Game_Action.EFFECT_ADD_DEBUFF:
        return !target.isMaxDebuffAffected(effect.dataId);
    case Game_Action.EFFECT_REMOVE_BUFF:
        return target.isBuffAffected(effect.dataId);
    case Game_Action.EFFECT_REMOVE_DEBUFF:
        return target.isDebuffAffected(effect.dataId);
    case Game_Action.EFFECT_LEARN_SKILL:
        return target.isActor() &amp;&amp; !target.isLearnedSkill(effect.dataId);
    default:
        return true;
    }
};

/* 项目反击值 */
Game_Action.prototype.itemCnt = function(target) {
    if (this.isPhysical() &amp;&amp; target.canMove()) {
        return target.cnt;
    } else {
        return 0;
    }
};

/* 项目魔法反射值 */
Game_Action.prototype.itemMrf = function(target) {
    if (this.isMagical()) {
        return target.mrf;
    } else {
        return 0;
    }
};

/* 项目命中率值 */
Game_Action.prototype.itemHit = function(target) {
    if (this.isPhysical()) {
        return this.item().successRate * 0.01 * this.subject().hit;
    } else {
        return this.item().successRate * 0.01;
    }
};

/* 项目回避率值 */
Game_Action.prototype.itemEva = function(target) {
    if (this.isPhysical()) {
        return target.eva;
    } else if (this.isMagical()) {
        return target.mev;
    } else {
        return 0;
    }
};

/* 项目暴击率值 */
Game_Action.prototype.itemCri = function(target) {
    return this.item().damage.critical ? this.subject().cri * (1 - target.cev) : 0;
};

/* 执行 */
Game_Action.prototype.apply = function(target) {
    var result = target.result();
    this.subject().clearResult();
    result.clear();
    result.used = this.testApply(target);
    result.missed = (result.used &amp;&amp; Math.random() &gt;= this.itemHit(target));
    result.evaded = (!result.missed &amp;&amp; Math.random() &lt; this.itemEva(target));
    result.physical = this.isPhysical();
    result.drain = this.isDrain();
    if (result.isHit()) {
        if (this.item().damage.type &gt; 0) {
            result.critical = (Math.random() &lt; this.itemCri(target));
            var value = this.makeDamageValue(target, result.critical);
            this.executeDamage(target, value);
        }
        this.item().effects.forEach(function(effect) {
            this.applyItemEffect(target, effect);
        }, this);
        this.applyItemUserEffect(target);
    }
};

/* 制作伤害值 */
Game_Action.prototype.makeDamageValue = function(target, critical) {
    var item = this.item();
    var baseValue = this.evalDamageFormula(target);
    var value = baseValue * this.calcElementRate(target);
    if (this.isPhysical()) {
        value *= target.pdr;
    }
    if (this.isMagical()) {
        value *= target.mdr;
    }
    if (baseValue &lt; 0) {
        value *= target.rec;
    }
    if (critical) {
        value = this.applyCritical(value);
    }
    value = this.applyVariance(value, item.damage.variance);
    value = this.applyGuard(value, target);
    value = Math.round(value);
    return value;
};

/* 求值伤害表达式 */
Game_Action.prototype.evalDamageFormula = function(target) {
    try {
        var item = this.item();
        var a = this.subject();
        var b = target;
        var v = $gameVariables._data;
        var sign = ([3, 4].contains(item.damage.type) ? -1 : 1);
        var value = Math.max(eval(item.damage.formula), 0) * sign;
		if (isNaN(value)) value = 0;
		return value;
    } catch (e) {
        return 0;
    }
};

/* 计算属性有效度 */
Game_Action.prototype.calcElementRate = function(target) {
    if (this.item().damage.elementId &lt; 0) {
        return this.elementsMaxRate(target, this.subject().attackElements());
    } else {
        return target.elementRate(this.item().damage.elementId);
    }
};

/* 属性最高有效度 */
Game_Action.prototype.elementsMaxRate = function(target, elements) {
    if (elements.length &gt; 0) {
        return Math.max.apply(null, elements.map(function(elementId) {
            return target.elementRate(elementId);
        }, this));
    } else {
        return 1;
    }
};

/* 执行暴击 */
Game_Action.prototype.applyCritical = function(damage) {
    return damage * 3;
};

/* 执行分散度 */
Game_Action.prototype.applyVariance = function(damage, variance) {
    var amp = Math.floor(Math.max(Math.abs(damage) * variance / 100, 0));
    var v = Math.randomInt(amp + 1) + Math.randomInt(amp + 1) - amp;
    return damage &gt;= 0 ? damage + v : damage - v;
};

/* 执行防御 */
Game_Action.prototype.applyGuard = function(damage, target) {
    return damage / (damage &gt; 0 &amp;&amp; target.isGuard() ? 2 * target.grd : 1);
};

/* 执行伤害 */
Game_Action.prototype.executeDamage = function(target, value) {
    var result = target.result();
    if (value === 0) {
        result.critical = false;
    }
    if (this.isHpEffect()) {
        this.executeHpDamage(target, value);
    }
    if (this.isMpEffect()) {
        this.executeMpDamage(target, value);
    }
};

/* 执行 HP 伤害 */
Game_Action.prototype.executeHpDamage = function(target, value) {
    if (this.isDrain()) {
        value = Math.min(target.hp, value);
    }
    this.makeSuccess(target);
    target.gainHp(-value);
    if (value &gt; 0) {
        target.onDamage(value);
    }
    this.gainDrainedHp(value);
};

/* 执行 MP 伤害 */
Game_Action.prototype.executeMpDamage = function(target, value) {
    if (!this.isMpRecover()) {
        value = Math.min(target.mp, value);
    }
    if (value !== 0) {
        this.makeSuccess(target);
    }
    target.gainMp(-value);
    this.gainDrainedMp(value);
};

/* 获得吸收的 HP */
Game_Action.prototype.gainDrainedHp = function(value) {
    if (this.isDrain()) {
       var gainTarget = this.subject();
       if (this._reflectionTarget !== undefined) {
            gainTarget = this._reflectionTarget;
        }
       gainTarget.gainHp(value);
    }
};

/* 获得吸收的 MP */
Game_Action.prototype.gainDrainedMp = function(value) {
    if (this.isDrain()) {
       var gainTarget = this.subject();
       if (this._reflectionTarget !== undefined) {
           gainTarget = this._reflectionTarget;
       }
       gainTarget.gainMp(value);
    }
};

/* 执行项目效果 */
Game_Action.prototype.applyItemEffect = function(target, effect) {
    switch (effect.code) {
    case Game_Action.EFFECT_RECOVER_HP:
        this.itemEffectRecoverHp(target, effect);
        break;
    case Game_Action.EFFECT_RECOVER_MP:
        this.itemEffectRecoverMp(target, effect);
        break;
    case Game_Action.EFFECT_GAIN_TP:
        this.itemEffectGainTp(target, effect);
        break;
    case Game_Action.EFFECT_ADD_STATE:
        this.itemEffectAddState(target, effect);
        break;
    case Game_Action.EFFECT_REMOVE_STATE:
        this.itemEffectRemoveState(target, effect);
        break;
    case Game_Action.EFFECT_ADD_BUFF:
        this.itemEffectAddBuff(target, effect);
        break;
    case Game_Action.EFFECT_ADD_DEBUFF:
        this.itemEffectAddDebuff(target, effect);
        break;
    case Game_Action.EFFECT_REMOVE_BUFF:
        this.itemEffectRemoveBuff(target, effect);
        break;
    case Game_Action.EFFECT_REMOVE_DEBUFF:
        this.itemEffectRemoveDebuff(target, effect);
        break;
    case Game_Action.EFFECT_SPECIAL:
        this.itemEffectSpecial(target, effect);
        break;
    case Game_Action.EFFECT_GROW:
        this.itemEffectGrow(target, effect);
        break;
    case Game_Action.EFFECT_LEARN_SKILL:
        this.itemEffectLearnSkill(target, effect);
        break;
    case Game_Action.EFFECT_COMMON_EVENT:
        this.itemEffectCommonEvent(target, effect);
        break;
    }
};

/* 项目效果-恢复 HP */
Game_Action.prototype.itemEffectRecoverHp = function(target, effect) {
    var value = (target.mhp * effect.value1 + effect.value2) * target.rec;
    if (this.isItem()) {
        value *= this.subject().pha;
    }
    value = Math.floor(value);
    if (value !== 0) {
        target.gainHp(value);
        this.makeSuccess(target);
    }
};

/* 项目效果-恢复 MP */
Game_Action.prototype.itemEffectRecoverMp = function(target, effect) {
    var value = (target.mmp * effect.value1 + effect.value2) * target.rec;
    if (this.isItem()) {
        value *= this.subject().pha;
    }
    value = Math.floor(value);
    if (value !== 0) {
        target.gainMp(value);
        this.makeSuccess(target);
    }
};

/* 项目效果-获得 TP */
Game_Action.prototype.itemEffectGainTp = function(target, effect) {
    var value = Math.floor(effect.value1);
    if (value !== 0) {
        target.gainTp(value);
        this.makeSuccess(target);
    }
};

/* 项目效果-附加状态 */
Game_Action.prototype.itemEffectAddState = function(target, effect) {
    if (effect.dataId === 0) {
        this.itemEffectAddAttackState(target, effect);
    } else {
        this.itemEffectAddNormalState(target, effect);
    }
};

/* 项目效果-附加普通攻击状态 */
Game_Action.prototype.itemEffectAddAttackState = function(target, effect) {
    this.subject().attackStates().forEach(function(stateId) {
        var chance = effect.value1;
        chance *= target.stateRate(stateId);
        chance *= this.subject().attackStatesRate(stateId);
        chance *= this.lukEffectRate(target);
        if (Math.random() &lt; chance) {
            target.addState(stateId);
            this.makeSuccess(target);
        }
    }.bind(this), target);
};

/* 项目效果-附加普通状态 */
Game_Action.prototype.itemEffectAddNormalState = function(target, effect) {
    var chance = effect.value1;
    if (!this.isCertainHit()) {
        chance *= target.stateRate(effect.dataId);
        chance *= this.lukEffectRate(target);
    }
    if (Math.random() &lt; chance) {
        target.addState(effect.dataId);
        this.makeSuccess(target);
    }
};

/* 项目效果-解除状态 */
Game_Action.prototype.itemEffectRemoveState = function(target, effect) {
    var chance = effect.value1;
    if (Math.random() &lt; chance) {
        target.removeState(effect.dataId);
        this.makeSuccess(target);
    }
};

/* 项目效果-强化 */
Game_Action.prototype.itemEffectAddBuff = function(target, effect) {
    target.addBuff(effect.dataId, effect.value1);
    this.makeSuccess(target);
};

/* 项目效果-弱化 */
Game_Action.prototype.itemEffectAddDebuff = function(target, effect) {
    var chance = target.debuffRate(effect.dataId) * this.lukEffectRate(target);
    if (Math.random() &lt; chance) {
        target.addDebuff(effect.dataId, effect.value1);
        this.makeSuccess(target);
    }
};

/* 项目效果-解除强化 */
Game_Action.prototype.itemEffectRemoveBuff = function(target, effect) {
    if (target.isBuffAffected(effect.dataId)) {
        target.removeBuff(effect.dataId);
        this.makeSuccess(target);
    }
};

/* 项目效果-解除弱化 */
Game_Action.prototype.itemEffectRemoveDebuff = function(target, effect) {
    if (target.isDebuffAffected(effect.dataId)) {
        target.removeBuff(effect.dataId);
        this.makeSuccess(target);
    }
};

/* 项目效果-特殊效果 */
Game_Action.prototype.itemEffectSpecial = function(target, effect) {
    if (effect.dataId === Game_Action.SPECIAL_EFFECT_ESCAPE) {
        target.escape();
        this.makeSuccess(target);
    }
};

/* 项目效果-成长 */
Game_Action.prototype.itemEffectGrow = function(target, effect) {
    target.addParam(effect.dataId, Math.floor(effect.value1));
    this.makeSuccess(target);
};

/* 项目效果-学会技能 */
Game_Action.prototype.itemEffectLearnSkill = function(target, effect) {
    if (target.isActor()) {
        target.learnSkill(effect.dataId);
        this.makeSuccess(target);
    }
};

/* 项目效果-公共事件 */
Game_Action.prototype.itemEffectCommonEvent = function(target, effect) {
};

/* 制作成功 */
Game_Action.prototype.makeSuccess = function(target) {
    target.result().success = true;
};

/* 执行项目使用者效果 */
Game_Action.prototype.applyItemUserEffect = function(target) {
    var value = Math.floor(this.item().tpGain * this.subject().tcr);
    this.subject().gainSilentTp(value);
};

/* 幸运效果变化率 */
Game_Action.prototype.lukEffectRate = function(target) {
    return Math.max(1.0 + (this.subject().luk - target.luk) * 0.001, 0.0);
};

/* 执行全局 */
Game_Action.prototype.applyGlobal = function() {
    this.item().effects.forEach(function(effect) {
        if (effect.code === Game_Action.EFFECT_COMMON_EVENT) {
            $gameTemp.reserveCommonEvent(effect.dataId);
        }
    }, this);
};

//-----------------------------------------------------------------------------
// 游戏_行动结果
// Game_ActionResult
//
// 战斗行动结果的游戏对象类。为了方便起见，此类中的所有成员变量都是公共的。
// The game object class for a result of a battle action. For convinience, all
// member variables in this class are public.

function Game_ActionResult() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_ActionResult.prototype.initialize = function() {
    this.clear();
};

/* 清除 */
Game_ActionResult.prototype.clear = function() {
    this.used = false;
    this.missed = false;
    this.evaded = false;
    this.physical = false;
    this.drain = false;
    this.critical = false;
    this.success = false;
    this.hpAffected = false;
    this.hpDamage = 0;
    this.mpDamage = 0;
    this.tpDamage = 0;
    this.addedStates = [];
    this.removedStates = [];
    this.addedBuffs = [];
    this.addedDebuffs = [];
    this.removedBuffs = [];
};

/* 附加状态对象 */
Game_ActionResult.prototype.addedStateObjects = function() {
    return this.addedStates.map(function(id) {
        return $dataStates[id];
    });
};

/* 移除状态对象 */
Game_ActionResult.prototype.removedStateObjects = function() {
    return this.removedStates.map(function(id) {
        return $dataStates[id];
    });
};

/* 是否有受影响的状态 */
Game_ActionResult.prototype.isStatusAffected = function() {
    return (this.addedStates.length &gt; 0 || this.removedStates.length &gt; 0 ||
            this.addedBuffs.length &gt; 0 || this.addedDebuffs.length &gt; 0 ||
            this.removedBuffs.length &gt; 0);
};

/* 是否命中 */
Game_ActionResult.prototype.isHit = function() {
    return this.used &amp;&amp; !this.missed &amp;&amp; !this.evaded;
};

/* 该状态是否附加 */
Game_ActionResult.prototype.isStateAdded = function(stateId) {
    return this.addedStates.contains(stateId);
};

/* 增加附加的状态 */
Game_ActionResult.prototype.pushAddedState = function(stateId) {
    if (!this.isStateAdded(stateId)) {
        this.addedStates.push(stateId);
    }
};

/* 该状态是否解除 */
Game_ActionResult.prototype.isStateRemoved = function(stateId) {
    return this.removedStates.contains(stateId);
};

/* 增加解除的状态 */
Game_ActionResult.prototype.pushRemovedState = function(stateId) {
    if (!this.isStateRemoved(stateId)) {
        this.removedStates.push(stateId);
    }
};
/* 该强化效果是否附加 */
Game_ActionResult.prototype.isBuffAdded = function(paramId) {
    return this.addedBuffs.contains(paramId);
};

/* 增加附加的强化效果 */
Game_ActionResult.prototype.pushAddedBuff = function(paramId) {
    if (!this.isBuffAdded(paramId)) {
        this.addedBuffs.push(paramId);
    }
};

/* 该弱化效果是否附加 */
Game_ActionResult.prototype.isDebuffAdded = function(paramId) {
    return this.addedDebuffs.contains(paramId);
};

/* 增加附加的弱化效果 */
Game_ActionResult.prototype.pushAddedDebuff = function(paramId) {
    if (!this.isDebuffAdded(paramId)) {
        this.addedDebuffs.push(paramId);
    }
};

/* 该强化效果是否解除 */
Game_ActionResult.prototype.isBuffRemoved = function(paramId) {
    return this.removedBuffs.contains(paramId);
};

/* 增加解除的强化效果 */
Game_ActionResult.prototype.pushRemovedBuff = function(paramId) {
    if (!this.isBuffRemoved(paramId)) {
        this.removedBuffs.push(paramId);
    }
};

//-----------------------------------------------------------------------------
// 游戏_战斗基础
// Game_BattlerBase
//
// Game_Battler 的父类。它主要包括能力值计算。
// The superclass of Game_Battler. It mainly contains parameters calculation.

function Game_BattlerBase() {
    this.initialize.apply(this, arguments);
}

Game_BattlerBase.TRAIT_ELEMENT_RATE   = 11;  // 特性 - 属性有效度 
Game_BattlerBase.TRAIT_DEBUFF_RATE    = 12;  // 特性 - 弱化有效度 
Game_BattlerBase.TRAIT_STATE_RATE     = 13;  // 特性 - 状态有效度 
Game_BattlerBase.TRAIT_STATE_RESIST   = 14;  // 特性 - 状态免疫 
Game_BattlerBase.TRAIT_PARAM          = 21;  // 特性 - 通常能力值 
Game_BattlerBase.TRAIT_XPARAM         = 22;  // 特性 - 追加能力值 
Game_BattlerBase.TRAIT_SPARAM         = 23;  // 特性 - 特殊能力值 
Game_BattlerBase.TRAIT_ATTACK_ELEMENT = 31;  // 特性 - 攻击时属性 
Game_BattlerBase.TRAIT_ATTACK_STATE   = 32;  // 特性 - 攻击时状态 
Game_BattlerBase.TRAIT_ATTACK_SPEED   = 33;  // 特性 - 攻击时速度补正 
Game_BattlerBase.TRAIT_ATTACK_TIMES   = 34;  // 特性 - 攻击追加次数 
Game_BattlerBase.TRAIT_STYPE_ADD      = 41;  // 特性 - 添加技能类型 
Game_BattlerBase.TRAIT_STYPE_SEAL     = 42;  // 特性 - 封印技能类型 
Game_BattlerBase.TRAIT_SKILL_ADD      = 43;  // 特性 - 添加技能 
Game_BattlerBase.TRAIT_SKILL_SEAL     = 44;  // 特性 - 封印技能 
Game_BattlerBase.TRAIT_EQUIP_WTYPE    = 51;  // 特性 - 装备武器类型 
Game_BattlerBase.TRAIT_EQUIP_ATYPE    = 52;  // 特性 - 装备护甲类型 
Game_BattlerBase.TRAIT_EQUIP_LOCK     = 53;  // 特性 - 固定装备 
Game_BattlerBase.TRAIT_EQUIP_SEAL     = 54;  // 特性 - 封印装备 
Game_BattlerBase.TRAIT_SLOT_TYPE      = 55;  // 特性 - 装备槽类型 
Game_BattlerBase.TRAIT_ACTION_PLUS    = 61;  // 特性 - 增加行动次数 
Game_BattlerBase.TRAIT_SPECIAL_FLAG   = 62;  // 特性 - 特殊标志 
Game_BattlerBase.TRAIT_COLLAPSE_TYPE  = 63;  // 特性 - 消失效果 
Game_BattlerBase.TRAIT_PARTY_ABILITY  = 64;  // 特性 - 队伍能力 
Game_BattlerBase.FLAG_ID_AUTO_BATTLE  = 0;   // 特殊标志 - 自动战斗 
Game_BattlerBase.FLAG_ID_GUARD        = 1;   // 特殊标志 - 防御 
Game_BattlerBase.FLAG_ID_SUBSTITUTE   = 2;   // 特殊标志 - 掩护 
Game_BattlerBase.FLAG_ID_PRESERVE_TP  = 3;   // 特殊标志 - 保留 TP 
Game_BattlerBase.ICON_BUFF_START      = 32;  // 强化状态图标起始索引 
Game_BattlerBase.ICON_DEBUFF_START    = 48;  // 弱化状态图标起始索引 

Object.defineProperties(Game_BattlerBase.prototype, {
    // 生命值（Hit Points） 
    hp: { get: function() { return this._hp; }, configurable: true },
    // 魔法值（Magic Points） 
    mp: { get: function() { return this._mp; }, configurable: true },
    // 怒气值（Tactical Points） 
    tp: { get: function() { return this._tp; }, configurable: true },
    // 最大生命值（Maximum Hit Points） 
    mhp: { get: function() { return this.param(0); }, configurable: true },
    // 最大魔法值（Maximum Magic Points） 
    mmp: { get: function() { return this.param(1); }, configurable: true },
    // 攻击力（ATtacK power） 
    atk: { get: function() { return this.param(2); }, configurable: true },
    // 防御力（DEFense power） 
    def: { get: function() { return this.param(3); }, configurable: true },
    // 魔法攻击（Magic ATtack power） 
    mat: { get: function() { return this.param(4); }, configurable: true },
    // 魔法防御（Magic DeFense power） 
    mdf: { get: function() { return this.param(5); }, configurable: true },
    // 敏捷（AGIlity） 
    agi: { get: function() { return this.param(6); }, configurable: true },
    // 运气（LUcK） 
    luk: { get: function() { return this.param(7); }, configurable: true },
    // 命中率（HIT rate） 
    hit: { get: function() { return this.xparam(0); }, configurable: true },
    // 回避率（EVAsion rate） 
    eva: { get: function() { return this.xparam(1); }, configurable: true },
    // 暴击率（CRItical rate） 
    cri: { get: function() { return this.xparam(2); }, configurable: true },
    // 暴击回避（Critical EVasion rate） 
    cev: { get: function() { return this.xparam(3); }, configurable: true },
    // 魔法回避（Magic EVasion rate） 
    mev: { get: function() { return this.xparam(4); }, configurable: true },
    // 魔法反射（Magic ReFlection rate） 
    mrf: { get: function() { return this.xparam(5); }, configurable: true },
    // 反击（CouNTer attack rate） 
    cnt: { get: function() { return this.xparam(6); }, configurable: true },
    // HP 自动恢复（Hp ReGeneration rate） 
    hrg: { get: function() { return this.xparam(7); }, configurable: true },
    // MP 自动恢复（Mp ReGeneration rate） 
    mrg: { get: function() { return this.xparam(8); }, configurable: true },
    // TP 自动恢复（Tp ReGeneration rate） 
    trg: { get: function() { return this.xparam(9); }, configurable: true },
    // 受到攻击几率（TarGet Rate） 
    tgr: { get: function() { return this.sparam(0); }, configurable: true },
    // 防御效果（GuaRD effect rate），影响防御时的伤害，伤害为1/(2*grd) 
    grd: { get: function() { return this.sparam(1); }, configurable: true },
    // 恢复效果（RECovery effect rate），影响恢复 HP 和 MP 的百分比（取决于被治疗者，物品技能皆有效） 
    rec: { get: function() { return this.sparam(2); }, configurable: true },
    // 药理知识（PHArmacology），影响使用物品时恢复 HP 和 MP 的百分比（取决于使用者，技能无效） 
    pha: { get: function() { return this.sparam(3); }, configurable: true },
    // MP 消耗量（Mp Cost Rate） 
    mcr: { get: function() { return this.sparam(4); }, configurable: true },
    // TP 补充率（Tp Charge Rate） 
    tcr: { get: function() { return this.sparam(5); }, configurable: true },
    // 物理伤害（Physical Damage Rate） 
    pdr: { get: function() { return this.sparam(6); }, configurable: true },
    // 魔法伤害（Magical Damage Rate） 
    mdr: { get: function() { return this.sparam(7); }, configurable: true },
    // 地形伤害（Floor Damage Rate） 
    fdr: { get: function() { return this.sparam(8); }, configurable: true },
    // 经验值（EXperience Rate） 
    exr: { get: function() { return this.sparam(9); }, configurable: true }
});

/* 初始化 */
Game_BattlerBase.prototype.initialize = function() {
    this.initMembers();
};

/* 初始化成员 */
Game_BattlerBase.prototype.initMembers = function() {
    this._hp = 1;
    this._mp = 0;
    this._tp = 0;
    this._hidden = false;
    this.clearParamPlus();
    this.clearStates();
    this.clearBuffs();
};

/* 清除增加的能力值 */
Game_BattlerBase.prototype.clearParamPlus = function() {
    this._paramPlus = [0,0,0,0,0,0,0,0];
};

/* 清除状态 */
Game_BattlerBase.prototype.clearStates = function() {
    this._states = [];
    this._stateTurns = {};
};

/* 消除该状态 */
Game_BattlerBase.prototype.eraseState = function(stateId) {
    var index = this._states.indexOf(stateId);
    if (index &gt;= 0) {
        this._states.splice(index, 1);
    }
    delete this._stateTurns[stateId];
};

/* 是否受该状态影响 */
Game_BattlerBase.prototype.isStateAffected = function(stateId) {
    return this._states.contains(stateId);
};

/* 是否受无法战斗状态影响 */
Game_BattlerBase.prototype.isDeathStateAffected = function() {
    return this.isStateAffected(this.deathStateId());
};

/* 无法战斗状态 ID */
Game_BattlerBase.prototype.deathStateId = function() {
    return 1;
};

/* 重置状态计数 */
Game_BattlerBase.prototype.resetStateCounts = function(stateId) {
    var state = $dataStates[stateId];
    var variance = 1 + Math.max(state.maxTurns - state.minTurns, 0);
    this._stateTurns[stateId] = state.minTurns + Math.randomInt(variance);
};

/* 该状态是否失效 */
Game_BattlerBase.prototype.isStateExpired = function(stateId) {
    return this._stateTurns[stateId] === 0;
};

/* 更新状态回合 */
Game_BattlerBase.prototype.updateStateTurns = function() {
    this._states.forEach(function(stateId) {
        if (this._stateTurns[stateId] &gt; 0) {
            this._stateTurns[stateId]--;
        }
    }, this);
};

/* 清除强化效果 */
Game_BattlerBase.prototype.clearBuffs = function() {
    this._buffs = [0,0,0,0,0,0,0,0];
    this._buffTurns = [0,0,0,0,0,0,0,0];
};

/* 消除该强化效果 */
Game_BattlerBase.prototype.eraseBuff = function(paramId) {
    this._buffs[paramId] = 0;
    this._buffTurns[paramId] = 0;
};

/* 强化效果个数 */
Game_BattlerBase.prototype.buffLength = function() {
    return this._buffs.length;
};

/* 强化效果 */
Game_BattlerBase.prototype.buff = function(paramId) {
    return this._buffs[paramId];
};

/* 是否受该强化效果影响 */
Game_BattlerBase.prototype.isBuffAffected = function(paramId) {
    return this._buffs[paramId] &gt; 0;
};

/* 是否受该弱化效果影响 */
Game_BattlerBase.prototype.isDebuffAffected = function(paramId) {
    return this._buffs[paramId] &lt; 0;
};

/* 是否受该强化或弱化效果影响 */
Game_BattlerBase.prototype.isBuffOrDebuffAffected = function(paramId) {
    return this._buffs[paramId] !== 0;
};

/* 该受影响的强化效果是否达到最大级数 */
Game_BattlerBase.prototype.isMaxBuffAffected = function(paramId) {
    return this._buffs[paramId] === 2;
};

/* 该受影响的弱化效果是否达到最大级数 */
Game_BattlerBase.prototype.isMaxDebuffAffected = function(paramId) {
    return this._buffs[paramId] === -2;
};

/* 增加强化效果级数 */
Game_BattlerBase.prototype.increaseBuff = function(paramId) {
    if (!this.isMaxBuffAffected(paramId)) {
        this._buffs[paramId];
    }
};

/* 减少强化效果级数 */
Game_BattlerBase.prototype.decreaseBuff = function(paramId) {
    if (!this.isMaxDebuffAffected(paramId)) {
        this._buffs[paramId]--;
    }
};

/* 重写强化效果回合数 */
Game_BattlerBase.prototype.overwriteBuffTurns = function(paramId, turns) {
    if (this._buffTurns[paramId] &lt; turns) {
        this._buffTurns[paramId] = turns;
    }
};

/* 该强化效果是否失效 */
Game_BattlerBase.prototype.isBuffExpired = function(paramId) {
    return this._buffTurns[paramId] === 0;
};

/* 更新强化效果回合数 */
Game_BattlerBase.prototype.updateBuffTurns = function() {
    for (var i = 0; i &lt; this._buffTurns.length; i) {
        if (this._buffTurns[i] &gt; 0) {
            this._buffTurns[i]--;
        }
    }
};

/* 死亡 */
Game_BattlerBase.prototype.die = function() {
    this._hp = 0;
    this.clearStates();
    this.clearBuffs();
};

/* 复活 */
Game_BattlerBase.prototype.revive = function() {
    if (this._hp === 0) {
        this._hp = 1;
    }
};

/* 状态 */
Game_BattlerBase.prototype.states = function() {
    return this._states.map(function(id) {
        return $dataStates[id];
    });
};

/* 状态图标 */
Game_BattlerBase.prototype.stateIcons = function() {
    return this.states().map(function(state) {
        return state.iconIndex;
    }).filter(function(iconIndex) {
        return iconIndex &gt; 0;
    });
};

/* 强化效果图标 */
Game_BattlerBase.prototype.buffIcons = function() {
    var icons = [];
    for (var i = 0; i &lt; this._buffs.length; i) {
        if (this._buffs[i] !== 0) {
            icons.push(this.buffIconIndex(this._buffs[i], i));
        }
    }
    return icons;
};

/* 强化效果图标索引 */
Game_BattlerBase.prototype.buffIconIndex = function(buffLevel, paramId) {
    if (buffLevel &gt; 0) {
        return Game_BattlerBase.ICON_BUFF_START + (buffLevel - 1) * 8 + paramId;
    } else if (buffLevel &lt; 0) {
        return Game_BattlerBase.ICON_DEBUFF_START + (-buffLevel - 1) * 8 + paramId;
    } else {
        return 0;
    }
};

/* 所有图标 */
Game_BattlerBase.prototype.allIcons = function() {
    return this.stateIcons().concat(this.buffIcons());
};

/* 特征对象 */
Game_BattlerBase.prototype.traitObjects = function() {
    // Returns an array of the all objects having traits. States only here.
    return this.states();
};

/* 所有特征 */
Game_BattlerBase.prototype.allTraits = function() {
    return this.traitObjects().reduce(function(r, obj) {
        return r.concat(obj.traits);
    }, []);
};

/* 特征 */
Game_BattlerBase.prototype.traits = function(code) {
    return this.allTraits().filter(function(trait) {
        return trait.code === code;
    });
};

/* 根据 ID 获取特征 */
Game_BattlerBase.prototype.traitsWithId = function(code, id) {
    return this.allTraits().filter(function(trait) {
        return trait.code === code &amp;&amp; trait.dataId === id;
    });
};

/* 特征值求积 */
Game_BattlerBase.prototype.traitsPi = function(code, id) {
    return this.traitsWithId(code, id).reduce(function(r, trait) {
        return r * trait.value;
    }, 1);
};

/* 特征值求和 */
Game_BattlerBase.prototype.traitsSum = function(code, id) {
    return this.traitsWithId(code, id).reduce(function(r, trait) {
        return r + trait.value;
    }, 0);
};

/* 所有特征值求和 */
Game_BattlerBase.prototype.traitsSumAll = function(code) {
    return this.traits(code).reduce(function(r, trait) {
        return r + trait.value;
    }, 0);
};

/* 特征设置 */
Game_BattlerBase.prototype.traitsSet = function(code) {
    return this.traits(code).reduce(function(r, trait) {
        return r.concat(trait.dataId);
    }, []);
};

/* 基础能力值 */
Game_BattlerBase.prototype.paramBase = function(paramId) {
    return 0;
};

/* 增加的能力值*/
Game_BattlerBase.prototype.paramPlus = function(paramId) {
    return this._paramPlus[paramId];
};

/* 能力值最小值 */
Game_BattlerBase.prototype.paramMin = function(paramId) {
    if (paramId === 1) {
        return 0;   // MMP
    } else {
        return 1;
    }
};

/* 能力值最大值 */
Game_BattlerBase.prototype.paramMax = function(paramId) {
    if (paramId === 0) {
        return 999999;  // MHP
    } else if (paramId === 1) {
        return 9999;    // MMP
    } else {
        return 999;
    }
};

/* 能力值变化率 */
Game_BattlerBase.prototype.paramRate = function(paramId) {
    return this.traitsPi(Game_BattlerBase.TRAIT_PARAM, paramId);
};

/* 能力值强化倍率 */
Game_BattlerBase.prototype.paramBuffRate = function(paramId) {
    return this._buffs[paramId] * 0.25 + 1.0;
};

/* 能力值（各种加成计算后的最终值） */
Game_BattlerBase.prototype.param = function(paramId) {
    var value = this.paramBase(paramId) + this.paramPlus(paramId);
    value *= this.paramRate(paramId) * this.paramBuffRate(paramId);
    var maxValue = this.paramMax(paramId);
    var minValue = this.paramMin(paramId);
    return Math.round(value.clamp(minValue, maxValue));
};

/* 追加能力值 */
Game_BattlerBase.prototype.xparam = function(xparamId) {
    return this.traitsSum(Game_BattlerBase.TRAIT_XPARAM, xparamId);
};

/* 特殊能力值 */
Game_BattlerBase.prototype.sparam = function(sparamId) {
    return this.traitsPi(Game_BattlerBase.TRAIT_SPARAM, sparamId);
};

/* 属性有效度 */
Game_BattlerBase.prototype.elementRate = function(elementId) {
    return this.traitsPi(Game_BattlerBase.TRAIT_ELEMENT_RATE, elementId);
};

/* 弱化有效度 */
Game_BattlerBase.prototype.debuffRate = function(paramId) {
    return this.traitsPi(Game_BattlerBase.TRAIT_DEBUFF_RATE, paramId);
};

/* 状态有效度 */
Game_BattlerBase.prototype.stateRate = function(stateId) {
    return this.traitsPi(Game_BattlerBase.TRAIT_STATE_RATE, stateId);
};

/* 状态免疫设置 */
Game_BattlerBase.prototype.stateResistSet = function() {
    return this.traitsSet(Game_BattlerBase.TRAIT_STATE_RESIST);
};

/* 是否免疫该状态 */
Game_BattlerBase.prototype.isStateResist = function(stateId) {
    return this.stateResistSet().contains(stateId);
};

/* 攻击时属性 */
Game_BattlerBase.prototype.attackElements = function() {
    return this.traitsSet(Game_BattlerBase.TRAIT_ATTACK_ELEMENT);
};

/* 攻击时状态 */
Game_BattlerBase.prototype.attackStates = function() {
    return this.traitsSet(Game_BattlerBase.TRAIT_ATTACK_STATE);
};

/* 攻击时状态有效度 */
Game_BattlerBase.prototype.attackStatesRate = function(stateId) {
    return this.traitsSum(Game_BattlerBase.TRAIT_ATTACK_STATE, stateId);
};

/* 攻击时速度补正 */
Game_BattlerBase.prototype.attackSpeed = function() {
    return this.traitsSumAll(Game_BattlerBase.TRAIT_ATTACK_SPEED);
};

/* 攻击追加次数 */
Game_BattlerBase.prototype.attackTimesAdd = function() {
    return Math.max(this.traitsSumAll(Game_BattlerBase.TRAIT_ATTACK_TIMES), 0);
};

/* 添加的技能类型 */
Game_BattlerBase.prototype.addedSkillTypes = function() {
    return this.traitsSet(Game_BattlerBase.TRAIT_STYPE_ADD);
};

/* 是否被封印的技能类型 */
Game_BattlerBase.prototype.isSkillTypeSealed = function(stypeId) {
    return this.traitsSet(Game_BattlerBase.TRAIT_STYPE_SEAL).contains(stypeId);
};

/* 添加的技能 */
Game_BattlerBase.prototype.addedSkills = function() {
    return this.traitsSet(Game_BattlerBase.TRAIT_SKILL_ADD);
};

/* 是否被封印该技能 */
Game_BattlerBase.prototype.isSkillSealed = function(skillId) {
    return this.traitsSet(Game_BattlerBase.TRAIT_SKILL_SEAL).contains(skillId);
};

/* 是否允许装备该武器类型 */
Game_BattlerBase.prototype.isEquipWtypeOk = function(wtypeId) {
    return this.traitsSet(Game_BattlerBase.TRAIT_EQUIP_WTYPE).contains(wtypeId);
};

/* 是否允许装备该护甲类型 */
Game_BattlerBase.prototype.isEquipAtypeOk = function(atypeId) {
    return this.traitsSet(Game_BattlerBase.TRAIT_EQUIP_ATYPE).contains(atypeId);
};

/* 是否固定该部位的装备 */
Game_BattlerBase.prototype.isEquipTypeLocked = function(etypeId) {
    return this.traitsSet(Game_BattlerBase.TRAIT_EQUIP_LOCK).contains(etypeId);
};

/* 是否封印该部位的装备 */
Game_BattlerBase.prototype.isEquipTypeSealed = function(etypeId) {
    return this.traitsSet(Game_BattlerBase.TRAIT_EQUIP_SEAL).contains(etypeId);
};

/* 装备槽类型 */
Game_BattlerBase.prototype.slotType = function() {
    var set = this.traitsSet(Game_BattlerBase.TRAIT_SLOT_TYPE);
    return set.length &gt; 0 ? Math.max.apply(null, set) : 0;
};

/* 是否二刀流 */
Game_BattlerBase.prototype.isDualWield = function() {
    return this.slotType() === 1;
};

/* 增加行动次数设置 */
Game_BattlerBase.prototype.actionPlusSet = function() {
    return this.traits(Game_BattlerBase.TRAIT_ACTION_PLUS).map(function(trait) {
        return trait.value;
    });
};

/* 是否有该特殊标志 */
Game_BattlerBase.prototype.specialFlag = function(flagId) {
    return this.traits(Game_BattlerBase.TRAIT_SPECIAL_FLAG).some(function(trait) {
        return trait.dataId === flagId;
    });
};

/* 消失效果类型 */
Game_BattlerBase.prototype.collapseType = function() {
    var set = this.traitsSet(Game_BattlerBase.TRAIT_COLLAPSE_TYPE);
    return set.length &gt; 0 ? Math.max.apply(null, set) : 0;
};

/* 是否有该队伍能力 */
Game_BattlerBase.prototype.partyAbility = function(abilityId) {
    return this.traits(Game_BattlerBase.TRAIT_PARTY_ABILITY).some(function(trait) {
        return trait.dataId === abilityId;
    });
};

/* 是否自动战斗 */
Game_BattlerBase.prototype.isAutoBattle = function() {
    return this.specialFlag(Game_BattlerBase.FLAG_ID_AUTO_BATTLE);
};

/* 是否防御 */
Game_BattlerBase.prototype.isGuard = function() {
    return this.specialFlag(Game_BattlerBase.FLAG_ID_GUARD) &amp;&amp; this.canMove();
};

/* 是否掩护 */
Game_BattlerBase.prototype.isSubstitute = function() {
    return this.specialFlag(Game_BattlerBase.FLAG_ID_SUBSTITUTE) &amp;&amp; this.canMove();
};

/* 是否保留 TP */
Game_BattlerBase.prototype.isPreserveTp = function() {
    return this.specialFlag(Game_BattlerBase.FLAG_ID_PRESERVE_TP);
};

/* 增加能力值 */
Game_BattlerBase.prototype.addParam = function(paramId, value) {
    this._paramPlus[paramId] += value;
    this.refresh();
};

/* 设置 HP */
Game_BattlerBase.prototype.setHp = function(hp) {
    this._hp = hp;
    this.refresh();
};

/* 设置 MP */
Game_BattlerBase.prototype.setMp = function(mp) {
    this._mp = mp;
    this.refresh();
};

/* 设置 TP */
Game_BattlerBase.prototype.setTp = function(tp) {
    this._tp = tp;
    this.refresh();
};

/* TP 最大值 */
Game_BattlerBase.prototype.maxTp = function() {
    return 100;
};

/* 刷新 */
Game_BattlerBase.prototype.refresh = function() {
    this.stateResistSet().forEach(function(stateId) {
        this.eraseState(stateId);
    }, this);
    this._hp = this._hp.clamp(0, this.mhp);
    this._mp = this._mp.clamp(0, this.mmp);
    this._tp = this._tp.clamp(0, this.maxTp());
};

/* 恢复全部 */
Game_BattlerBase.prototype.recoverAll = function() {
    this.clearStates();
    this._hp = this.mhp;
    this._mp = this.mmp;
};

/* HP 比例 */
Game_BattlerBase.prototype.hpRate = function() {
    return this.hp / this.mhp;
};

/* MP 比例 */
Game_BattlerBase.prototype.mpRate = function() {
    return this.mmp &gt; 0 ? this.mp / this.mmp : 0;
};

/* TP 比例 */
Game_BattlerBase.prototype.tpRate = function() {
    return this.tp / this.maxTp();
};

/* 隐藏 */
Game_BattlerBase.prototype.hide = function() {
    this._hidden = true;
};

/* 出现 */
Game_BattlerBase.prototype.appear = function() {
    this._hidden = false;
};

/* 是否隐藏 */
Game_BattlerBase.prototype.isHidden = function() {
    return this._hidden;
};

/* 是否出现 */
Game_BattlerBase.prototype.isAppeared = function() {
    return !this.isHidden();
};

/* 是否死亡 */
Game_BattlerBase.prototype.isDead = function() {
    return this.isAppeared() &amp;&amp; this.isDeathStateAffected();
};

/* 是否活着 */
Game_BattlerBase.prototype.isAlive = function() {
    return this.isAppeared() &amp;&amp; !this.isDeathStateAffected();
};

/* 是否频死 */
Game_BattlerBase.prototype.isDying = function() {
    return this.isAlive() &amp;&amp; this._hp &lt; this.mhp / 4;
};

/* 是否行动被限制 */
Game_BattlerBase.prototype.isRestricted = function() {
    return this.isAppeared() &amp;&amp; this.restriction() &gt; 0;
};

/* 是否可输入指令 */
Game_BattlerBase.prototype.canInput = function() {
    return this.isAppeared() &amp;&amp; !this.isRestricted() &amp;&amp; !this.isAutoBattle();
};

/* 是否可移动 */
Game_BattlerBase.prototype.canMove = function() {
    return this.isAppeared() &amp;&amp; this.restriction() &lt; 4;
};

/* 是否混乱 */
Game_BattlerBase.prototype.isConfused = function() {
    return this.isAppeared() &amp;&amp; this.restriction() &gt;= 1 &amp;&amp; this.restriction() &lt;= 3;
};

/* 混乱等级 */
Game_BattlerBase.prototype.confusionLevel = function() {
    return this.isConfused() ? this.restriction() : 0;
};

/* 是否是玩家 */
Game_BattlerBase.prototype.isActor = function() {
    return false;
};

/* 是否是敌人 */
Game_BattlerBase.prototype.isEnemy = function() {
    return false;
};

/* 排序状态 */
Game_BattlerBase.prototype.sortStates = function() {
    this._states.sort(function(a, b) {
        var p1 = $dataStates[a].priority;
        var p2 = $dataStates[b].priority;
        if (p1 !== p2) {
            return p2 - p1;
        }
        return a - b;
    });
};

/* 限制 */
Game_BattlerBase.prototype.restriction = function() {
    return Math.max.apply(null, this.states().map(function(state) {
        return state.restriction;
    }).concat(0));
};

/* 增加新状态 */
Game_BattlerBase.prototype.addNewState = function(stateId) {
    if (stateId === this.deathStateId()) {
        this.die();
    }
    var restricted = this.isRestricted();
    this._states.push(stateId);
    this.sortStates();
    if (!restricted &amp;&amp; this.isRestricted()) {
        this.onRestrict();
    }
};

/* 当限制 */
Game_BattlerBase.prototype.onRestrict = function() {
};

/* 最重要的状态文本 
 * 指的是状态-信息-状态持续时。 
 */
Game_BattlerBase.prototype.mostImportantStateText = function() {
    var states = this.states();
    for (var i = 0; i &lt; states.length; i) {
        if (states[i].message3) {
            return states[i].message3;
        }
    }
    return '';
};

/* 状态动作索引 
 * 指的是状态-基本设置-[SV]动作，0：正常，1：状态异常，2：睡眠，3：无法战斗。
 */
Game_BattlerBase.prototype.stateMotionIndex = function() {
    var states = this.states();
    if (states.length &gt; 0) {
        return states[0].motion;
    } else {
        return 0;
    }
};

/* 状态遮罩索引 
 * 指的是状态-基本设置-[SV]遮罩，0：无，1：中毒，2：黑暗，3：沉默，4：愤怒，5：混乱，6：魅惑，7：睡眠，8：麻痹，9：诅咒，10：恐惧。
 */
Game_BattlerBase.prototype.stateOverlayIndex = function() {
    var states = this.states();
    if (states.length &gt; 0) {
        return states[0].overlay;
    } else {
        return 0;
    }
};

/* 是否该技能满足需要的武器类型 
 * Game_Actor 会重写该函数。
 */
Game_BattlerBase.prototype.isSkillWtypeOk = function(skill) {
    return true;
};

/* 技能 MP 消耗 */
Game_BattlerBase.prototype.skillMpCost = function(skill) {
    return Math.floor(skill.mpCost * this.mcr);
};

/* 技能 TP 消耗 */
Game_BattlerBase.prototype.skillTpCost = function(skill) {
    return skill.tpCost;
};

/* 是否能够支付技能消耗 */
Game_BattlerBase.prototype.canPaySkillCost = function(skill) {
    return this._tp &gt;= this.skillTpCost(skill) &amp;&amp; this._mp &gt;= this.skillMpCost(skill);
};

/* 支付技能消耗 */
Game_BattlerBase.prototype.paySkillCost = function(skill) {
    this._mp -= this.skillMpCost(skill);
    this._tp -= this.skillTpCost(skill);
};

/* 是否该物品可使用的场合 
 * occasion 为物品-基本设置-使用场合，0：随时使用，1：战斗画面，2：菜单画面，3：不能使用。
 */
Game_BattlerBase.prototype.isOccasionOk = function(item) {
    if ($gameParty.inBattle()) {
        return item.occasion === 0 || item.occasion === 1;
    } else {
        return item.occasion === 0 || item.occasion === 2;
    }
};

/* 是否符合可用物品条件 */
Game_BattlerBase.prototype.meetsUsableItemConditions = function(item) {
    return this.canMove() &amp;&amp; this.isOccasionOk(item);
};

/* 是否符合技能条件 */
Game_BattlerBase.prototype.meetsSkillConditions = function(skill) {
    return (this.meetsUsableItemConditions(skill) &amp;&amp;
            this.isSkillWtypeOk(skill) &amp;&amp; this.canPaySkillCost(skill) &amp;&amp;
            !this.isSkillSealed(skill.id) &amp;&amp; !this.isSkillTypeSealed(skill.stypeId));
};

/* 是否符合物品条件 */
Game_BattlerBase.prototype.meetsItemConditions = function(item) {
    return this.meetsUsableItemConditions(item) &amp;&amp; $gameParty.hasItem(item);
};

/* 是否可使用 */
Game_BattlerBase.prototype.canUse = function(item) {
    if (!item) {
        return false;
    } else if (DataManager.isSkill(item)) {
        return this.meetsSkillConditions(item);
    } else if (DataManager.isItem(item)) {
        return this.meetsItemConditions(item);
    } else {
        return false;
    }
};

/* 是否可装备 */
Game_BattlerBase.prototype.canEquip = function(item) {
    if (!item) {
        return false;
    } else if (DataManager.isWeapon(item)) {
        return this.canEquipWeapon(item);
    } else if (DataManager.isArmor(item)) {
        return this.canEquipArmor(item);
    } else {
        return false;
    }
};

/* 是否可装备该武器 */
Game_BattlerBase.prototype.canEquipWeapon = function(item) {
    return this.isEquipWtypeOk(item.wtypeId) &amp;&amp; !this.isEquipTypeSealed(item.etypeId);
};

/* 是否可装备该护甲 */
Game_BattlerBase.prototype.canEquipArmor = function(item) {
    return this.isEquipAtypeOk(item.atypeId) &amp;&amp; !this.isEquipTypeSealed(item.etypeId);
};

/* 普通攻击技能 ID */
Game_BattlerBase.prototype.attackSkillId = function() {
    return 1;
};

/* 防御技能 ID */
Game_BattlerBase.prototype.guardSkillId = function() {
    return 2;
};

/* 是否可以普通攻击 */
Game_BattlerBase.prototype.canAttack = function() {
    return this.canUse($dataSkills[this.attackSkillId()]);
};

/* 是否可以防御 */
Game_BattlerBase.prototype.canGuard = function() {
    return this.canUse($dataSkills[this.guardSkillId()]);
};

//-----------------------------------------------------------------------------
// 游戏_战斗者
// Game_Battler
//
// Game_Actor 和 Game_Enemy 的父类。它包含精灵和行动的方法。
// The superclass of Game_Actor and Game_Enemy. It contains methods for sprites
// and actions.

function Game_Battler() {
    this.initialize.apply(this, arguments);
}

Game_Battler.prototype = Object.create(Game_BattlerBase.prototype);
Game_Battler.prototype.constructor = Game_Battler;

/* 初始化 */
Game_Battler.prototype.initialize = function() {
    Game_BattlerBase.prototype.initialize.call(this);
};

/* 初始化成员 */
Game_Battler.prototype.initMembers = function() {
    Game_BattlerBase.prototype.initMembers.call(this);
    this._actions = [];
    this._speed = 0;
    this._result = new Game_ActionResult();
    this._actionState = '';
    this._lastTargetIndex = 0;
    this._animations = [];
    this._damagePopup = false;
    this._effectType = null;
    this._motionType = null;
    this._weaponImageId = 0;
    this._motionRefresh = false;
    this._selected = false;
};

/* 清除动画 */
Game_Battler.prototype.clearAnimations = function() {
    this._animations = [];
};

/* 清除伤害弹出层 */
Game_Battler.prototype.clearDamagePopup = function() {
    this._damagePopup = false;
};

/* 清除武器动画 */
Game_Battler.prototype.clearWeaponAnimation = function() {
    this._weaponImageId = 0;
};

/* 清除效果 */
Game_Battler.prototype.clearEffect = function() {
    this._effectType = null;
};

/* 清除动作 */
Game_Battler.prototype.clearMotion = function() {
    this._motionType = null;
    this._motionRefresh = false;
};

/* 请求效果 */
Game_Battler.prototype.requestEffect = function(effectType) {
    this._effectType = effectType;
};

/* 请求动作 */
Game_Battler.prototype.requestMotion = function(motionType) {
    this._motionType = motionType;
};

/* 请求动作刷新 */
Game_Battler.prototype.requestMotionRefresh = function() {
    this._motionRefresh = true;
};

/* 选择 */
Game_Battler.prototype.select = function() {
    this._selected = true;
};

/* 取消选择 */
Game_Battler.prototype.deselect = function() {
    this._selected = false;
};

/* 是否有动画请求 */
Game_Battler.prototype.isAnimationRequested = function() {
    return this._animations.length &gt; 0;
};

/* 是否有伤害弹出层请求 */
Game_Battler.prototype.isDamagePopupRequested = function() {
    return this._damagePopup;
};

/* 是否有效果请求 */
Game_Battler.prototype.isEffectRequested = function() {
    return !!this._effectType;
};

/* 是否有动作请求 */
Game_Battler.prototype.isMotionRequested = function() {
    return !!this._motionType;
};

/* 是否有武器动画请求 */
Game_Battler.prototype.isWeaponAnimationRequested = function() {
    return this._weaponImageId &gt; 0;
};

/* 是否有动作刷新请求 */
Game_Battler.prototype.isMotionRefreshRequested = function() {
    return this._motionRefresh;
};

/* 是否选择 */
Game_Battler.prototype.isSelected = function() {
    return this._selected;
};

/* 效果类型 */
Game_Battler.prototype.effectType = function() {
    return this._effectType;
};

/* 动作类型 */
Game_Battler.prototype.motionType = function() {
    return this._motionType;
};

/* 武器图像 ID */
Game_Battler.prototype.weaponImageId = function() {
    return this._weaponImageId;
};

/* 转移动画 
 * 将动画数组的第一个元素从其中删除，并返回第一个元素的值。
 */
Game_Battler.prototype.shiftAnimation = function() {
    return this._animations.shift();
};

/* 开始动画 */
Game_Battler.prototype.startAnimation = function(animationId, mirror, delay) {
    var data = { animationId: animationId, mirror: mirror, delay: delay };
    this._animations.push(data);
};

/* 开始伤害弹出层 */
Game_Battler.prototype.startDamagePopup = function() {
    this._damagePopup = true;
};

/* 开始武器动画 */
Game_Battler.prototype.startWeaponAnimation = function(weaponImageId) {
    this._weaponImageId = weaponImageId;
};

/* 行动 */
Game_Battler.prototype.action = function(index) {
    return this._actions[index];
};

/* 设置行动 */
Game_Battler.prototype.setAction = function(index, action) {
    this._actions[index] = action;
};

/* 行动个数 */
Game_Battler.prototype.numActions = function() {
    return this._actions.length;
};

/* 清除行动 */
Game_Battler.prototype.clearActions = function() {
    this._actions = [];
};

/* 结果 */
Game_Battler.prototype.result = function() {
    return this._result;
};

/* 清除结果 */
Game_Battler.prototype.clearResult = function() {
    this._result.clear();
};

/* 刷新 */
Game_Battler.prototype.refresh = function() {
    Game_BattlerBase.prototype.refresh.call(this);
    if (this.hp === 0) {
        this.addState(this.deathStateId());
    } else {
        this.removeState(this.deathStateId());
    }
};

/* 添加状态 */
Game_Battler.prototype.addState = function(stateId) {
    if (this.isStateAddable(stateId)) {
        if (!this.isStateAffected(stateId)) {
            this.addNewState(stateId);
            this.refresh();
        }
        this.resetStateCounts(stateId);
        this._result.pushAddedState(stateId);
    }
};

/* 该状态是否可添加 */
Game_Battler.prototype.isStateAddable = function(stateId) {
    return (this.isAlive() &amp;&amp; $dataStates[stateId] &amp;&amp;
            !this.isStateResist(stateId) &amp;&amp;
            !this._result.isStateRemoved(stateId) &amp;&amp;
            !this.isStateRestrict(stateId));
};

/* 该状态是否受到行动限制时解除 */
Game_Battler.prototype.isStateRestrict = function(stateId) {
    return $dataStates[stateId].removeByRestriction &amp;&amp; this.isRestricted();
};

/* 当行动限制 */
Game_Battler.prototype.onRestrict = function() {
    Game_BattlerBase.prototype.onRestrict.call(this);
    this.clearActions();
    this.states().forEach(function(state) {
        if (state.removeByRestriction) {
            this.removeState(state.id);
        }
    }, this);
};

/* 解除状态 */
Game_Battler.prototype.removeState = function(stateId) {
    if (this.isStateAffected(stateId)) {
        if (stateId === this.deathStateId()) {
            this.revive();
        }
        this.eraseState(stateId);
        this.refresh();
        this._result.pushRemovedState(stateId);
    }
};

/* 逃跑 */
Game_Battler.prototype.escape = function() {
    if ($gameParty.inBattle()) {
        this.hide();
    }
    this.clearActions();
    this.clearStates();
    SoundManager.playEscape();
};

/* 添加强化 */
Game_Battler.prototype.addBuff = function(paramId, turns) {
    if (this.isAlive()) {
        this.increaseBuff(paramId);
        if (this.isBuffAffected(paramId)) {
            this.overwriteBuffTurns(paramId, turns);
        }
        this._result.pushAddedBuff(paramId);
        this.refresh();
    }
};

/* 添加弱化 */
Game_Battler.prototype.addDebuff = function(paramId, turns) {
    if (this.isAlive()) {
        this.decreaseBuff(paramId);
        if (this.isDebuffAffected(paramId)) {
            this.overwriteBuffTurns(paramId, turns);
        }
        this._result.pushAddedDebuff(paramId);
        this.refresh();
    }
};

/* 解除强化 */
Game_Battler.prototype.removeBuff = function(paramId) {
    if (this.isAlive() &amp;&amp; this.isBuffOrDebuffAffected(paramId)) {
        this.eraseBuff(paramId);
        this._result.pushRemovedBuff(paramId);
        this.refresh();
    }
};

/* 解除战斗状态 */
Game_Battler.prototype.removeBattleStates = function() {
    this.states().forEach(function(state) {
        if (state.removeAtBattleEnd) {
            this.removeState(state.id);
        }
    }, this);
};

/* 解除所有强化 */
Game_Battler.prototype.removeAllBuffs = function() {
    for (var i = 0; i &lt; this.buffLength(); i) {
        this.removeBuff(i);
    }
};

/* 自动解除状态 */
Game_Battler.prototype.removeStatesAuto = function(timing) {
    this.states().forEach(function(state) {
        if (this.isStateExpired(state.id) &amp;&amp; state.autoRemovalTiming === timing) {
            this.removeState(state.id);
        }
    }, this);
};

/* 自动解除强化 */
Game_Battler.prototype.removeBuffsAuto = function() {
    for (var i = 0; i &lt; this.buffLength(); i) {
        if (this.isBuffExpired(i)) {
            this.removeBuff(i);
        }
    }
};

/* 受伤时解除状态 */
Game_Battler.prototype.removeStatesByDamage = function() {
    this.states().forEach(function(state) {
        if (state.removeByDamage &amp;&amp; Math.randomInt(100) &lt; state.chanceByDamage) {
            this.removeState(state.id);
        }
    }, this);
};

/* 制作行动次数 */
Game_Battler.prototype.makeActionTimes = function() {
    return this.actionPlusSet().reduce(function(r, p) {
        return Math.random() &lt; p ? r + 1 : r;
    }, 1);
};

/* 制作行动 */
Game_Battler.prototype.makeActions = function() {
    this.clearActions();
    if (this.canMove()) {
        var actionTimes = this.makeActionTimes();
        this._actions = [];
        for (var i = 0; i &lt; actionTimes; i) {
            this._actions.push(new Game_Action(this));
        }
    }
};

/* 速度 */
Game_Battler.prototype.speed = function() {
    return this._speed;
};

/* 制作速度 */
Game_Battler.prototype.makeSpeed = function() {
    this._speed = Math.min.apply(null, this._actions.map(function(action) {
        return action.speed();
    })) || 0;
};

/* 当前行动 */
Game_Battler.prototype.currentAction = function() {
    return this._actions[0];
};

/* 移除当前行动 */
Game_Battler.prototype.removeCurrentAction = function() {
    this._actions.shift();
};

/* 设置上次目标 */
Game_Battler.prototype.setLastTarget = function(target) {
    if (target) {
        this._lastTargetIndex = target.index();
    } else {
        this._lastTargetIndex = 0;
    }
};

/* 强制行动 */
Game_Battler.prototype.forceAction = function(skillId, targetIndex) {
    this.clearActions();
    var action = new Game_Action(this, true);
    action.setSkill(skillId);
    if (targetIndex === -2) {
        action.setTarget(this._lastTargetIndex);
    } else if (targetIndex === -1) {
        action.decideRandomTarget();
    } else {
        action.setTarget(targetIndex);
    }
    this._actions.push(action);
};

/* 使用项目（技能和物品） */
Game_Battler.prototype.useItem = function(item) {
    if (DataManager.isSkill(item)) {
        this.paySkillCost(item);
    } else if (DataManager.isItem(item)) {
        this.consumeItem(item);
    }
};

/* 消耗物品 */
Game_Battler.prototype.consumeItem = function(item) {
    $gameParty.consumeItem(item);
};

/* 获得 HP */
Game_Battler.prototype.gainHp = function(value) {
    this._result.hpDamage = -value;
    this._result.hpAffected = true;
    this.setHp(this.hp + value);
};

/* 获得 MP */
Game_Battler.prototype.gainMp = function(value) {
    this._result.mpDamage = -value;
    this.setMp(this.mp + value);
};

/* 获得 TP */
Game_Battler.prototype.gainTp = function(value) {
    this._result.tpDamage = -value;
    this.setTp(this.tp + value);
};

/* 静默获得 TP 
 * 指改变 TP 值的时候不做显示。
 */
Game_Battler.prototype.gainSilentTp = function(value) {
    this.setTp(this.tp + value);
};

/* 初始化 TP */
Game_Battler.prototype.initTp = function() {
    this.setTp(Math.randomInt(25));
};

/* 清除 TP */
Game_Battler.prototype.clearTp = function() {
    this.setTp(0);
};

/* 受伤害时改变 TP */
Game_Battler.prototype.chargeTpByDamage = function(damageRate) {
    var value = Math.floor(50 * damageRate * this.tcr);
    this.gainSilentTp(value);
};

/* 自动恢复 HP */
Game_Battler.prototype.regenerateHp = function() {
    var value = Math.floor(this.mhp * this.hrg);
    value = Math.max(value, -this.maxSlipDamage());
    if (value !== 0) {
        this.gainHp(value);
    }
};

/* 最大移动伤害 */
Game_Battler.prototype.maxSlipDamage = function() {
    return $dataSystem.optSlipDeath ? this.hp : Math.max(this.hp - 1, 0);
};

/* 自动恢复 MP */
Game_Battler.prototype.regenerateMp = function() {
    var value = Math.floor(this.mmp * this.mrg);
    if (value !== 0) {
        this.gainMp(value);
    }
};

/* 自动恢复 TP */
Game_Battler.prototype.regenerateTp = function() {
    var value = Math.floor(100 * this.trg);
    this.gainSilentTp(value);
};

/* 自动恢复所有 */
Game_Battler.prototype.regenerateAll = function() {
    if (this.isAlive()) {
        this.regenerateHp();
        this.regenerateMp();
        this.regenerateTp();
    }
};

/* 当战斗开始 */
Game_Battler.prototype.onBattleStart = function() {
    this.setActionState('undecided');
    this.clearMotion();
    if (!this.isPreserveTp()) {
        this.initTp();
    }
};

/* 当所有行动结束 */
Game_Battler.prototype.onAllActionsEnd = function() {
    this.clearResult();
    this.removeStatesAuto(1);
    this.removeBuffsAuto();
};

/* 当回合结束 */
Game_Battler.prototype.onTurnEnd = function() {
    this.clearResult();
    this.regenerateAll();
    if (!BattleManager.isForcedTurn()) {
        this.updateStateTurns();
        this.updateBuffTurns();
    }
    this.removeStatesAuto(2);
};

/* 当战斗结束 */
Game_Battler.prototype.onBattleEnd = function() {
    this.clearResult();
    this.removeBattleStates();
    this.removeAllBuffs();
    this.clearActions();
    if (!this.isPreserveTp()) {
        this.clearTp();
    }
    this.appear();
};

/* 当受到伤害 */
Game_Battler.prototype.onDamage = function(value) {
    this.removeStatesByDamage();
    this.chargeTpByDamage(value / this.mhp);
};

/* 设置行动状态 */
Game_Battler.prototype.setActionState = function(actionState) {
    this._actionState = actionState;
    this.requestMotionRefresh();
};

/* 行动状态是否为未决定 */
Game_Battler.prototype.isUndecided = function() {
    return this._actionState === 'undecided';
};

/* 行动状态是否为输入中 */
Game_Battler.prototype.isInputting = function() {
    return this._actionState === 'inputting';
};

/* 行动状态是否为等待中 */
Game_Battler.prototype.isWaiting = function() {
    return this._actionState === 'waiting';
};

/* 行动状态是否为行动中 */
Game_Battler.prototype.isActing = function() {
    return this._actionState === 'acting';
};

/* 是否为吟唱中 */
Game_Battler.prototype.isChanting = function() {
    if (this.isWaiting()) {
        return this._actions.some(function(action) {
            return action.isMagicSkill();
        });
    }
    return false;
};

/* 是否防御等待中 */
Game_Battler.prototype.isGuardWaiting = function() {
    if (this.isWaiting()) {
        return this._actions.some(function(action) {
            return action.isGuard();
        });
    }
    return false;
};

/* 表现行动开始 */
Game_Battler.prototype.performActionStart = function(action) {
    if (!action.isGuard()) {
        this.setActionState('acting');
    }
};

/* 表现行动 */
Game_Battler.prototype.performAction = function(action) {
};

/* 表现行动结束 */
Game_Battler.prototype.performActionEnd = function() {
    this.setActionState('done');
};

/* 表现伤害 */
Game_Battler.prototype.performDamage = function() {
};

/* 表现未命中 */
Game_Battler.prototype.performMiss = function() {
    SoundManager.playMiss();
};

/* 表现恢复 */
Game_Battler.prototype.performRecovery = function() {
    SoundManager.playRecovery();
};

/* 表现闪避 */
Game_Battler.prototype.performEvasion = function() {
    SoundManager.playEvasion();
};

/* 表现魔法闪避 */
Game_Battler.prototype.performMagicEvasion = function() {
    SoundManager.playMagicEvasion();
};

/* 表现反击 */
Game_Battler.prototype.performCounter = function() {
    SoundManager.playEvasion();
};

/* 表现反射 */
Game_Battler.prototype.performReflection = function() {
    SoundManager.playReflection();
};

/* 表现掩护 */
Game_Battler.prototype.performSubstitute = function(target) {
};

/* 表现倒下（死亡后的消失效果） */
Game_Battler.prototype.performCollapse = function() {
};

//-----------------------------------------------------------------------------
// 游戏_角色
// Game_Actor
//
// 角色的游戏对象类。
// The game object class for an actor.

function Game_Actor() {
    this.initialize.apply(this, arguments);
}

Game_Actor.prototype = Object.create(Game_Battler.prototype);
Game_Actor.prototype.constructor = Game_Actor;

/* 等级 */
Object.defineProperty(Game_Actor.prototype, 'level', {
    get: function() {
        return this._level;
    },
    configurable: true
});

/* 初始化 */
Game_Actor.prototype.initialize = function(actorId) {
    Game_Battler.prototype.initialize.call(this);
    this.setup(actorId);
};

/* 初始化成员 */
Game_Actor.prototype.initMembers = function() {
    Game_Battler.prototype.initMembers.call(this);
    this._actorId = 0;
    this._name = '';
    this._nickname = '';
    this._classId = 0;
    this._level = 0;
    this._characterName = '';
    this._characterIndex = 0;
    this._faceName = '';
    this._faceIndex = 0;
    this._battlerName = '';
    this._exp = {};
    this._skills = [];
    this._equips = [];
    this._actionInputIndex = 0;
    this._lastMenuSkill = new Game_Item();
    this._lastBattleSkill  = new Game_Item();
    this._lastCommandSymbol = '';
};

/* 设置 */
Game_Actor.prototype.setup = function(actorId) {
    var actor = $dataActors[actorId];
    this._actorId = actorId;
    this._name = actor.name;
    this._nickname = actor.nickname;
    this._profile = actor.profile;
    this._classId = actor.classId;
    this._level = actor.initialLevel;
    this.initImages();
    this.initExp();
    this.initSkills();
    this.initEquips(actor.equips);
    this.clearParamPlus();
    this.recoverAll();
};

/* 角色 ID */
Game_Actor.prototype.actorId = function() {
    return this._actorId;
};

/* 角色 */
Game_Actor.prototype.actor = function() {
    return $dataActors[this._actorId];
};

/* 名称 */
Game_Actor.prototype.name = function() {
    return this._name;
};

/* 设置名称 */
Game_Actor.prototype.setName = function(name) {
    this._name = name;
};

/* 昵称 */
Game_Actor.prototype.nickname = function() {
    return this._nickname;
};

/* 设置昵称 */
Game_Actor.prototype.setNickname = function(nickname) {
    this._nickname = nickname;
};

/* 简介 */
Game_Actor.prototype.profile = function() {
    return this._profile;
};

/* 设置简介 */
Game_Actor.prototype.setProfile = function(profile) {
    this._profile = profile;
};

/* 行走图名称 */
Game_Actor.prototype.characterName = function() {
    return this._characterName;
};

/* 行走图索引 */
Game_Actor.prototype.characterIndex = function() {
    return this._characterIndex;
};

/* 脸图名称 */
Game_Actor.prototype.faceName = function() {
    return this._faceName;
};

/* 脸图索引 */
Game_Actor.prototype.faceIndex = function() {
    return this._faceIndex;
};

/* 战斗图名称 */
Game_Actor.prototype.battlerName = function() {
    return this._battlerName;
};

/* 清除状态数组 */
Game_Actor.prototype.clearStates = function() {
    Game_Battler.prototype.clearStates.call(this);
    this._stateSteps = {};
};

/* 消除状态 */
Game_Actor.prototype.eraseState = function(stateId) {
    Game_Battler.prototype.eraseState.call(this, stateId);
    delete this._stateSteps[stateId];
};

/* 重置状态计数 */
Game_Actor.prototype.resetStateCounts = function(stateId) {
    Game_Battler.prototype.resetStateCounts.call(this, stateId);
    this._stateSteps[stateId] = $dataStates[stateId].stepsToRemove;
};

/* 初始化图像 */
Game_Actor.prototype.initImages = function() {
    var actor = this.actor();
    this._characterName = actor.characterName;
    this._characterIndex = actor.characterIndex;
    this._faceName = actor.faceName;
    this._faceIndex = actor.faceIndex;
    this._battlerName = actor.battlerName;
};

/* 等级所对应的经验 */
Game_Actor.prototype.expForLevel = function(level) {
    var c = this.currentClass();
    var basis = c.expParams[0];
    var extra = c.expParams[1];
    var acc_a = c.expParams[2];
    var acc_b = c.expParams[3];
    return Math.round(basis*(Math.pow(level-1, 0.9+acc_a/250))*level*
            (level+1)/(6+Math.pow(level,2)/50/acc_b)(level-1)*extra);
};

/* 初始化经验 */
Game_Actor.prototype.initExp = function() {
    this._exp[this._classId] = this.currentLevelExp();
};

/* 当前经验 */
Game_Actor.prototype.currentExp = function() {
    return this._exp[this._classId];
};

/* 当前等级所对应的经验 */
Game_Actor.prototype.currentLevelExp = function() {
    return this.expForLevel(this._level);
};

/* 下一个等级所对应的经验 */
Game_Actor.prototype.nextLevelExp = function() {
    return this.expForLevel(this._level + 1);
};

/* 下一个等级所需经验 */
Game_Actor.prototype.nextRequiredExp = function() {
    return this.nextLevelExp() - this.currentExp();
};

/* 最大等级 */
Game_Actor.prototype.maxLevel = function() {
    return this.actor().maxLevel;
};

/* 是否最大等级 */
Game_Actor.prototype.isMaxLevel = function() {
    return this._level &gt;= this.maxLevel();
};

/* 初始化技能 */
Game_Actor.prototype.initSkills = function() {
    this._skills = [];
    this.currentClass().learnings.forEach(function(learning) {
        if (learning.level &lt;= this._level) {
            this.learnSkill(learning.skillId);
        }
    }, this);
};

/* 初始化装备 */
Game_Actor.prototype.initEquips = function(equips) {
    var slots = this.equipSlots();
    var maxSlots = slots.length;
    this._equips = [];
    for (var i = 0; i &lt; maxSlots; i) {
        this._equips[i] = new Game_Item();
    }
    for (var j = 0; j &lt; equips.length; j) {
        if (j &lt; maxSlots) {
            this._equips[j].setEquip(slots[j] === 1, equips[j]);
        }
    }
    this.releaseUnequippableItems(true);
    this.refresh();
};

/* 装备槽 */
Game_Actor.prototype.equipSlots = function() {
    var slots = [];
    for (var i = 1; i &lt; $dataSystem.equipTypes.length; i) {
        slots.push(i);
    }
    if (slots.length &gt;= 2 &amp;&amp; this.isDualWield()) {
        slots[1] = 1;
    }
    return slots;
};

/* 装备 */
Game_Actor.prototype.equips = function() {
    return this._equips.map(function(item) {
        return item.object();
    });
};

/* 武器 */
Game_Actor.prototype.weapons = function() {
    return this.equips().filter(function(item) {
        return item &amp;&amp; DataManager.isWeapon(item);
    });
};

/* 护甲 */
Game_Actor.prototype.armors = function() {
    return this.equips().filter(function(item) {
        return item &amp;&amp; DataManager.isArmor(item);
    });
};

/* 是否有该武器 */
Game_Actor.prototype.hasWeapon = function(weapon) {
    return this.weapons().contains(weapon);
};

/* 是否有该护甲 */
Game_Actor.prototype.hasArmor = function(armor) {
    return this.armors().contains(armor);
};

/* 该装备槽是否可以更换装备 */
Game_Actor.prototype.isEquipChangeOk = function(slotId) {
    return (!this.isEquipTypeLocked(this.equipSlots()[slotId]) &amp;&amp;
            !this.isEquipTypeSealed(this.equipSlots()[slotId]));
};

/* 更换装备 */
Game_Actor.prototype.changeEquip = function(slotId, item) {
    if (this.tradeItemWithParty(item, this.equips()[slotId]) &amp;&amp;
            (!item || this.equipSlots()[slotId] === item.etypeId)) {
        this._equips[slotId].setObject(item);
        this.refresh();
    }
};

/* 强制更换装备 */
Game_Actor.prototype.forceChangeEquip = function(slotId, item) {
    this._equips[slotId].setObject(item);
    this.releaseUnequippableItems(true);
    this.refresh();
};

/* 队伍交换物品 */
Game_Actor.prototype.tradeItemWithParty = function(newItem, oldItem) {
    if (newItem &amp;&amp; !$gameParty.hasItem(newItem)) {
        return false;
    } else {
        $gameParty.gainItem(oldItem, 1);
        $gameParty.loseItem(newItem, 1);
        return true;
    }
};

/* 通过 ID 更换装备 */
Game_Actor.prototype.changeEquipById = function(etypeId, itemId) {
    var slotId = etypeId - 1;
    if (this.equipSlots()[slotId] === 1) {
        this.changeEquip(slotId, $dataWeapons[itemId]);
    } else {
        this.changeEquip(slotId, $dataArmors[itemId]);
    }
};

/* 通是否装备 */
Game_Actor.prototype.isEquipped = function(item) {
    return this.equips().contains(item);
};

/* 丢弃装备 */
Game_Actor.prototype.discardEquip = function(item) {
    var slotId = this.equips().indexOf(item);
    if (slotId &gt;= 0) {
        this._equips[slotId].setObject(null);
    }
};

/* 解除不能装备的物品 */
Game_Actor.prototype.releaseUnequippableItems = function(forcing) {
    for (;;) {
        var slots = this.equipSlots();
        var equips = this.equips();
        var changed = false;
        for (var i = 0; i &lt; equips.length; i) {
            var item = equips[i];
            if (item &amp;&amp; (!this.canEquip(item) || item.etypeId !== slots[i])) {
                if (!forcing) {
                    this.tradeItemWithParty(null, item);
                }
                this._equips[i].setObject(null);
                changed = true;
            }
        }
        if (!changed) {
            break;
        }
    }
};

/* 清空装备 */
Game_Actor.prototype.clearEquipments = function() {
    var maxSlots = this.equipSlots().length;
    for (var i = 0; i &lt; maxSlots; i) {
        if (this.isEquipChangeOk(i)) {
            this.changeEquip(i, null);
        }
    }
};

/* 最强装备 */
Game_Actor.prototype.optimizeEquipments = function() {
    var maxSlots = this.equipSlots().length;
    this.clearEquipments();
    for (var i = 0; i &lt; maxSlots; i) {
        if (this.isEquipChangeOk(i)) {
            this.changeEquip(i, this.bestEquipItem(i));
        }
    }
};

/* 最强装备物品 */
Game_Actor.prototype.bestEquipItem = function(slotId) {
    var etypeId = this.equipSlots()[slotId];
    var items = $gameParty.equipItems().filter(function(item) {
        return item.etypeId === etypeId &amp;&amp; this.canEquip(item);
    }, this);
    var bestItem = null;
    var bestPerformance = -1000;
    for (var i = 0; i &lt; items.length; i) {
        var performance = this.calcEquipItemPerformance(items[i]);
        if (performance &gt; bestPerformance) {
            bestPerformance = performance;
            bestItem = items[i];
        }
    }
    return bestItem;
};

/* 计算装备物品性能 */
Game_Actor.prototype.calcEquipItemPerformance = function(item) {
    return item.params.reduce(function(a, b) {
        return a + b;
    });
};

/* 是否该技能满足需要的武器类型 */
Game_Actor.prototype.isSkillWtypeOk = function(skill) {
    var wtypeId1 = skill.requiredWtypeId1;
    var wtypeId2 = skill.requiredWtypeId2;
    if ((wtypeId1 === 0 &amp;&amp; wtypeId2 === 0) ||
            (wtypeId1 &gt; 0 &amp;&amp; this.isWtypeEquipped(wtypeId1)) ||
            (wtypeId2 &gt; 0 &amp;&amp; this.isWtypeEquipped(wtypeId2))) {
        return true;
    } else {
        return false;
    }
};

/* 是否装备的武器类型*/
Game_Actor.prototype.isWtypeEquipped = function(wtypeId) {
    return this.weapons().some(function(weapon) {
        return weapon.wtypeId === wtypeId;
    });
};

/* 刷新 */
Game_Actor.prototype.refresh = function() {
    this.releaseUnequippableItems(false);
    Game_Battler.prototype.refresh.call(this);
};

/* 是否角色 */
Game_Actor.prototype.isActor = function() {
    return true;
};

/* 我方单位 */
Game_Actor.prototype.friendsUnit = function() {
    return $gameParty;
};

/* 敌方单位 */
Game_Actor.prototype.opponentsUnit = function() {
    return $gameTroop;
};

/* 索引 */
Game_Actor.prototype.index = function() {
    return $gameParty.members().indexOf(this);
};

/* 是否战斗成员 */
Game_Actor.prototype.isBattleMember = function() {
    return $gameParty.battleMembers().contains(this);
};

/* 是否可以改变队形 */
Game_Actor.prototype.isFormationChangeOk = function() {
    return true;
};

/* 当前职业 */
Game_Actor.prototype.currentClass = function() {
    return $dataClasses[this._classId];
};

/* 是否是该职业 */
Game_Actor.prototype.isClass = function(gameClass) {
    return gameClass &amp;&amp; this._classId === gameClass.id;
};

/* 技能 */
Game_Actor.prototype.skills = function() {
    var list = [];
    this._skills.concat(this.addedSkills()).forEach(function(id) {
        if (!list.contains($dataSkills[id])) {
            list.push($dataSkills[id]);
        }
    });
    return list;
};

/* 可用的技能 */
Game_Actor.prototype.usableSkills = function() {
    return this.skills().filter(function(skill) {
        return this.canUse(skill);
    }, this);
};

/* 特征对象 */
Game_Actor.prototype.traitObjects = function() {
    var objects = Game_Battler.prototype.traitObjects.call(this);
    objects = objects.concat([this.actor(), this.currentClass()]);
    var equips = this.equips();
    for (var i = 0; i &lt; equips.length; i) {
        var item = equips[i];
        if (item) {
            objects.push(item);
        }
    }
    return objects;
};

/* 攻击时属性 */
Game_Actor.prototype.attackElements = function() {
    var set = Game_Battler.prototype.attackElements.call(this);
    if (this.hasNoWeapons() &amp;&amp; !set.contains(this.bareHandsElementId())) {
        set.push(this.bareHandsElementId());
    }
    return set;
};

/* 是否没武器 */
Game_Actor.prototype.hasNoWeapons = function() {
    return this.weapons().length === 0;
};

/* 空手属性 ID */
Game_Actor.prototype.bareHandsElementId = function() {
    return 1;
};

/* 能力值最大值 */
Game_Actor.prototype.paramMax = function(paramId) {
    if (paramId === 0) {
        return 9999;    // MHP
    }
    return Game_Battler.prototype.paramMax.call(this, paramId);
};

/* 基础能力值 */
Game_Actor.prototype.paramBase = function(paramId) {
    return this.currentClass().params[paramId][this._level];
};

/* 增加的能力值*/
Game_Actor.prototype.paramPlus = function(paramId) {
    var value = Game_Battler.prototype.paramPlus.call(this, paramId);
    var equips = this.equips();
    for (var i = 0; i &lt; equips.length; i) {
        var item = equips[i];
        if (item) {
            value += item.params[paramId];
        }
    }
    return value;
};

/* 攻击动画 1 ID */
Game_Actor.prototype.attackAnimationId1 = function() {
    if (this.hasNoWeapons()) {
        return this.bareHandsAnimationId();
    } else {
        var weapons = this.weapons();
        return weapons[0] ? weapons[0].animationId : 0;
    }
};

/* 攻击动画 2 ID */
Game_Actor.prototype.attackAnimationId2 = function() {
    var weapons = this.weapons();
    return weapons[1] ? weapons[1].animationId : 0;
};

/* 空手动画 ID */
Game_Actor.prototype.bareHandsAnimationId = function() {
    return 1;
};

/* 更改经验 */
Game_Actor.prototype.changeExp = function(exp, show) {
    this._exp[this._classId] = Math.max(exp, 0);
    var lastLevel = this._level;
    var lastSkills = this.skills();
    while (!this.isMaxLevel() &amp;&amp; this.currentExp() &gt;= this.nextLevelExp()) {
        this.levelUp();
    }
    while (this.currentExp() &lt; this.currentLevelExp()) {
        this.levelDown();
    }
    if (show &amp;&amp; this._level &gt; lastLevel) {
        this.displayLevelUp(this.findNewSkills(lastSkills));
    }
    this.refresh();
};

/* 升级 */
Game_Actor.prototype.levelUp = function() {
    this._level;
    this.currentClass().learnings.forEach(function(learning) {
        if (learning.level === this._level) {
            this.learnSkill(learning.skillId);
        }
    }, this);
};

/* 降级 */
Game_Actor.prototype.levelDown = function() {
    this._level--;
};

/* 寻找新技能 
 * 把升级后技能数组减去升级前技能数组元素，得到升级后新学的技能数组。
 */
Game_Actor.prototype.findNewSkills = function(lastSkills) {
    var newSkills = this.skills();
    for (var i = 0; i &lt; lastSkills.length; i) {
        var index = newSkills.indexOf(lastSkills[i]);
        if (index &gt;= 0) {
            newSkills.splice(index, 1);
        }
    }
    return newSkills;
};

/* 显示升级 */
Game_Actor.prototype.displayLevelUp = function(newSkills) {
    var text = TextManager.levelUp.format(this._name, TextManager.level, this._level);
    $gameMessage.newPage();
    $gameMessage.add(text);
    newSkills.forEach(function(skill) {
        $gameMessage.add(TextManager.obtainSkill.format(skill.name));
    });
};

/* 获得经验 */
Game_Actor.prototype.gainExp = function(exp) {
    var newExp = this.currentExp() + Math.round(exp * this.finalExpRate());
    this.changeExp(newExp, this.shouldDisplayLevelUp());
};

/* 最终经验比例 */
Game_Actor.prototype.finalExpRate = function() {
    return this.exr * (this.isBattleMember() ? 1 : this.benchMembersExpRate());
};

/* 替补队友经验比例 */
Game_Actor.prototype.benchMembersExpRate = function() {
    return $dataSystem.optExtraExp ? 1 : 0;
};

/* 是否应该显示升级 */
Game_Actor.prototype.shouldDisplayLevelUp = function() {
    return true;
};

/* 更改等级 */
Game_Actor.prototype.changeLevel = function(level, show) {
    level = level.clamp(1, this.maxLevel());
    this.changeExp(this.expForLevel(level), show);
};

/* 学习技能 */
Game_Actor.prototype.learnSkill = function(skillId) {
    if (!this.isLearnedSkill(skillId)) {
        this._skills.push(skillId);
        this._skills.sort(function(a, b) {
            return a - b;
        });
    }
};

/* 遗忘技能 */
Game_Actor.prototype.forgetSkill = function(skillId) {
    var index = this._skills.indexOf(skillId);
    if (index &gt;= 0) {
        this._skills.splice(index, 1);
    }
};

/* 是否已学的技能（不包括数据库直接添加的技能） */
Game_Actor.prototype.isLearnedSkill = function(skillId) {
    return this._skills.contains(skillId);
};

/* 是否有该技能 */
Game_Actor.prototype.hasSkill = function(skillId) {
    return this.skills().contains($dataSkills[skillId]);
};

/* 更改职业 */
Game_Actor.prototype.changeClass = function(classId, keepExp) {
    if (keepExp) {
        this._exp[classId] = this.currentExp();
    }
    this._classId = classId;
    this.changeExp(this._exp[this._classId] || 0, false);
    this.refresh();
};

/* 设置行走图图像 */
Game_Actor.prototype.setCharacterImage = function(characterName, characterIndex) {
    this._characterName = characterName;
    this._characterIndex = characterIndex;
};

/* 设置脸图图像 */
Game_Actor.prototype.setFaceImage = function(faceName, faceIndex) {
    this._faceName = faceName;
    this._faceIndex = faceIndex;
};

/* 设置战斗图图像 */
Game_Actor.prototype.setBattlerImage = function(battlerName) {
    this._battlerName = battlerName;
};

/* 精灵是否可见
 * 非测试图战斗模式下不显示角色。
 */
Game_Actor.prototype.isSpriteVisible = function() {
    return $gameSystem.isSideView();
};

/* 开始动画 */
Game_Actor.prototype.startAnimation = function(animationId, mirror, delay) {
    mirror = !mirror;
    Game_Battler.prototype.startAnimation.call(this, animationId, mirror, delay);
};

/* 表现行动开始 */
Game_Actor.prototype.performActionStart = function(action) {
    Game_Battler.prototype.performActionStart.call(this, action);
};

/* 表现行动 */
Game_Actor.prototype.performAction = function(action) {
    Game_Battler.prototype.performAction.call(this, action);
    if (action.isAttack()) {
        this.performAttack();
    } else if (action.isGuard()) {
        this.requestMotion('guard');
    } else if (action.isMagicSkill()) {
        this.requestMotion('spell');
    } else if (action.isSkill()) {
        this.requestMotion('skill');
    } else if (action.isItem()) {
        this.requestMotion('item');
    }
};

/* 表现行动结束 */
Game_Actor.prototype.performActionEnd = function() {
    Game_Battler.prototype.performActionEnd.call(this);
};

/* 表现攻击 */
Game_Actor.prototype.performAttack = function() {
    var weapons = this.weapons();
    var wtypeId = weapons[0] ? weapons[0].wtypeId : 0;
    var attackMotion = $dataSystem.attackMotions[wtypeId];
    if (attackMotion) {
        if (attackMotion.type === 0) {
            this.requestMotion('thrust');
        } else if (attackMotion.type === 1) {
            this.requestMotion('swing');
        } else if (attackMotion.type === 2) {
            this.requestMotion('missile');
        }
        this.startWeaponAnimation(attackMotion.weaponImageId);
    }
};

/* 表现伤害 */
Game_Actor.prototype.performDamage = function() {
    Game_Battler.prototype.performDamage.call(this);
    if (this.isSpriteVisible()) {
        this.requestMotion('damage');
    } else {
        $gameScreen.startShake(5, 5, 10);
    }
    SoundManager.playActorDamage();
};

/* 表现闪避 */
Game_Actor.prototype.performEvasion = function() {
    Game_Battler.prototype.performEvasion.call(this);
    this.requestMotion('evade');
};

/* 表现魔法闪避 */
Game_Actor.prototype.performMagicEvasion = function() {
    Game_Battler.prototype.performMagicEvasion.call(this);
    this.requestMotion('evade');
};

/* 表现反击 */
Game_Actor.prototype.performCounter = function() {
    Game_Battler.prototype.performCounter.call(this);
    this.performAttack();
};

/* 表现倒下（死亡后的消失效果） */
Game_Actor.prototype.performCollapse = function() {
    Game_Battler.prototype.performCollapse.call(this);
    if ($gameParty.inBattle()) {
        SoundManager.playActorCollapse();
    }
};

/* 表现胜利 */
Game_Actor.prototype.performVictory = function() {
    if (this.canMove()) {
        this.requestMotion('victory');
    }
};

/* 表现逃跑 */
Game_Actor.prototype.performEscape = function() {
    if (this.canMove()) {
        this.requestMotion('escape');
    }
};

/* 制作行动列表 */
Game_Actor.prototype.makeActionList = function() {
    var list = [];
    var action = new Game_Action(this);
    action.setAttack();
    list.push(action);
    this.usableSkills().forEach(function(skill) {
        action = new Game_Action(this);
        action.setSkill(skill.id);
        list.push(action);
    }, this);
    return list;
};

/* 制作自动战斗行动 */
Game_Actor.prototype.makeAutoBattleActions = function() {
    for (var i = 0; i &lt; this.numActions(); i) {
        var list = this.makeActionList();
        var maxValue = Number.MIN_VALUE;
        for (var j = 0; j &lt; list.length; j) {
            var value = list[j].evaluate();
            if (value &gt; maxValue) {
                maxValue = value;
                this.setAction(i, list[j]);
            }
        }
    }
    this.setActionState('waiting');
};

/* 制作混乱行动 */
Game_Actor.prototype.makeConfusionActions = function() {
    for (var i = 0; i &lt; this.numActions(); i) {
        this.action(i).setConfusion();
    }
    this.setActionState('waiting');
};

/* 制作行动 */
Game_Actor.prototype.makeActions = function() {
    Game_Battler.prototype.makeActions.call(this);
    if (this.numActions() &gt; 0) {
        this.setActionState('undecided');
    } else {
        this.setActionState('waiting');
    }
    if (this.isAutoBattle()) {
        this.makeAutoBattleActions();
    } else if (this.isConfused()) {
        this.makeConfusionActions();
    }
};

/* 当玩家行走 */
Game_Actor.prototype.onPlayerWalk = function() {
    this.clearResult();
    this.checkFloorEffect();
    if ($gamePlayer.isNormal()) {
        this.turnEndOnMap();
        this.states().forEach(function(state) {
            this.updateStateSteps(state);
        }, this);
        this.showAddedStates();
        this.showRemovedStates();
    }
};

/* 更新状态步数 */
Game_Actor.prototype.updateStateSteps = function(state) {
    if (state.removeByWalking) {
        if (this._stateSteps[state.id] &gt; 0) {
            if (--this._stateSteps[state.id] === 0) {
                this.removeState(state.id);
            }
        }
    }
};

/* 显示附加的状态 */
Game_Actor.prototype.showAddedStates = function() {
    this.result().addedStateObjects().forEach(function(state) {
        if (state.message1) {
            $gameMessage.add(this._name + state.message1);
        }
    }, this);
};

/* 显示解除的状态 */
Game_Actor.prototype.showRemovedStates = function() {
    this.result().removedStateObjects().forEach(function(state) {
        if (state.message4) {
            $gameMessage.add(this._name + state.message4);
        }
    }, this);
};

/* 回合的步数 */
Game_Actor.prototype.stepsForTurn = function() {
    return 20;
};

/* 地图上回合结束 */
Game_Actor.prototype.turnEndOnMap = function() {
    if ($gameParty.steps() % this.stepsForTurn() === 0) {
        this.onTurnEnd();
        if (this.result().hpDamage &gt; 0) {
            this.performMapDamage();
        }
    }
};

/* 检测地板效果 */
Game_Actor.prototype.checkFloorEffect = function() {
    if ($gamePlayer.isOnDamageFloor()) {
        this.executeFloorDamage();
    }
};

/* 执行低地板伤害 */
Game_Actor.prototype.executeFloorDamage = function() {
    var damage = Math.floor(this.basicFloorDamage() * this.fdr);
    damage = Math.min(damage, this.maxFloorDamage());
    this.gainHp(-damage);
    if (damage &gt; 0) {
        this.performMapDamage();
    }
};

/* 基础地板伤害 */
Game_Actor.prototype.basicFloorDamage = function() {
    return 10;
};

/* 最高地板伤害 */
Game_Actor.prototype.maxFloorDamage = function() {
    return $dataSystem.optFloorDeath ? this.hp : Math.max(this.hp - 1, 0);
};

/* 表现地图伤害 */
Game_Actor.prototype.performMapDamage = function() {
    if (!$gameParty.inBattle()) {
        $gameScreen.startFlashForDamage();
    }
};

/* 清除行动 */
Game_Actor.prototype.clearActions = function() {
    Game_Battler.prototype.clearActions.call(this);
    this._actionInputIndex = 0;
};

/* 行动输入中 */
Game_Actor.prototype.inputtingAction = function() {
    return this.action(this._actionInputIndex);
};

/* 选择下一个指令 */
Game_Actor.prototype.selectNextCommand = function() {
    if (this._actionInputIndex &lt; this.numActions() - 1) {
        this._actionInputIndex;
        return true;
    } else {
        return false;
    }
};

/* 选择先前的指令 */
Game_Actor.prototype.selectPreviousCommand = function() {
    if (this._actionInputIndex &gt; 0) {
        this._actionInputIndex--;
        return true;
    } else {
        return false;
    }
};

/* 上个菜单技能 */
Game_Actor.prototype.lastMenuSkill = function() {
    return this._lastMenuSkill.object();
};

/* 设置上个菜单技能 */
Game_Actor.prototype.setLastMenuSkill = function(skill) {
    this._lastMenuSkill.setObject(skill);
};

/* 上个战斗技能 */
Game_Actor.prototype.lastBattleSkill = function() {
    return this._lastBattleSkill.object();
};

/* 设置上个战斗技能 */
Game_Actor.prototype.setLastBattleSkill = function(skill) {
    this._lastBattleSkill.setObject(skill);
};

/* 上个指令标识 */
Game_Actor.prototype.lastCommandSymbol = function() {
    return this._lastCommandSymbol;
};

/* 设置上个指令标识 */
Game_Actor.prototype.setLastCommandSymbol = function(symbol) {
    this._lastCommandSymbol = symbol;
};

/* 检验逃跑 */
Game_Actor.prototype.testEscape = function(item) {
    return item.effects.some(function(effect, index, ar) {
        return effect &amp;&amp; effect.code === Game_Action.EFFECT_SPECIAL;
    });
};

/* 是否符合可用物品条件 */
Game_Actor.prototype.meetsUsableItemConditions = function(item) {
    if ($gameParty.inBattle() &amp;&amp; !BattleManager.canEscape() &amp;&amp; this.testEscape(item)) {
        return false;
    }
    return Game_BattlerBase.prototype.meetsUsableItemConditions.call(this, item);
};

//-----------------------------------------------------------------------------
// 游戏_敌人
// Game_Enemy
//
// 敌人的游戏对象类。
// The game object class for an enemy.

function Game_Enemy() {
    this.initialize.apply(this, arguments);
}

Game_Enemy.prototype = Object.create(Game_Battler.prototype);
Game_Enemy.prototype.constructor = Game_Enemy;

/* 初始化 */
Game_Enemy.prototype.initialize = function(enemyId, x, y) {
    Game_Battler.prototype.initialize.call(this);
    this.setup(enemyId, x, y);
};

/* 初始化成员 */
Game_Enemy.prototype.initMembers = function() {
    Game_Battler.prototype.initMembers.call(this);
    this._enemyId = 0;
    this._letter = '';
    this._plural = false;
    this._screenX = 0;
    this._screenY = 0;
};

/* 设置 */
Game_Enemy.prototype.setup = function(enemyId, x, y) {
    this._enemyId = enemyId;
    this._screenX = x;
    this._screenY = y;
    this.recoverAll();
};

/* 是否是敌人 */
Game_Enemy.prototype.isEnemy = function() {
    return true;
};

/* 我方单位 */
Game_Enemy.prototype.friendsUnit = function() {
    return $gameTroop;
};

/* 敌方单位 */
Game_Enemy.prototype.opponentsUnit = function() {
    return $gameParty;
};

/* 索引 */
Game_Enemy.prototype.index = function() {
    return $gameTroop.members().indexOf(this);
};

/* 是否是战斗成员 */
Game_Enemy.prototype.isBattleMember = function() {
    return this.index() &gt;= 0;
};

/* 敌人 ID */
Game_Enemy.prototype.enemyId = function() {
    return this._enemyId;
};

/* 敌人 */
Game_Enemy.prototype.enemy = function() {
    return $dataEnemies[this._enemyId];
};

/* 特征对象 */
Game_Enemy.prototype.traitObjects = function() {
    return Game_Battler.prototype.traitObjects.call(this).concat(this.enemy());
};

/* 基础能力值 */
Game_Enemy.prototype.paramBase = function(paramId) {
    return this.enemy().params[paramId];
};

/* 经验 */
Game_Enemy.prototype.exp = function() {
    return this.enemy().exp;
};

/* 金币 */
Game_Enemy.prototype.gold = function() {
    return this.enemy().gold;
};

/* 制作掉落物品 */
Game_Enemy.prototype.makeDropItems = function() {
    return this.enemy().dropItems.reduce(function(r, di) {
        if (di.kind &gt; 0 &amp;&amp; Math.random() * di.denominator &lt; this.dropItemRate()) {
            return r.concat(this.itemObject(di.kind, di.dataId));
        } else {
            return r;
        }
    }.bind(this), []);
};

/* 掉落物品比例 */
Game_Enemy.prototype.dropItemRate = function() {
    return $gameParty.hasDropItemDouble() ? 2 : 1;
};

/* 物品对象 */
Game_Enemy.prototype.itemObject = function(kind, dataId) {
    if (kind === 1) {
        return $dataItems[dataId];
    } else if (kind === 2) {
        return $dataWeapons[dataId];
    } else if (kind === 3) {
        return $dataArmors[dataId];
    } else {
        return null;
    }
};

/* 精灵是否可见 */
Game_Enemy.prototype.isSpriteVisible = function() {
    return true;
};

/* 画面 X 坐标 */
Game_Enemy.prototype.screenX = function() {
    return this._screenX;
};

/* 画面 Y 坐标 */
Game_Enemy.prototype.screenY = function() {
    return this._screenY;
};

/* 战斗图名字 */
Game_Enemy.prototype.battlerName = function() {
    return this.enemy().battlerName;
};

/* 战斗图色相 */
Game_Enemy.prototype.battlerHue = function() {
    return this.enemy().battlerHue;
};

/* 原名 */
Game_Enemy.prototype.originalName = function() {
    return this.enemy().name;
};

/* 战斗者名称  
 * 多只同样的敌人时，会在敌人原名后面加字母来区分。
 */
Game_Enemy.prototype.name = function() {
    return this.originalName() + (this._plural ? this._letter : '');
};

/* 是否字母为空 */
Game_Enemy.prototype.isLetterEmpty = function() {
    return this._letter === '';
};

/* 设置字母 */
Game_Enemy.prototype.setLetter = function(letter) {
    this._letter = letter;
};

/* 设置复数的 */
Game_Enemy.prototype.setPlural = function(plural) {
    this._plural = plural;
};

/* 表现行动开始 */
Game_Enemy.prototype.performActionStart = function(action) {
    Game_Battler.prototype.performActionStart.call(this, action);
    this.requestEffect('whiten');
};

/* 表现行动 */
Game_Enemy.prototype.performAction = function(action) {
    Game_Battler.prototype.performAction.call(this, action);
};

/* 表现行动结束 */
Game_Enemy.prototype.performActionEnd = function() {
    Game_Battler.prototype.performActionEnd.call(this);
};

/* 表现伤害 */
Game_Enemy.prototype.performDamage = function() {
    Game_Battler.prototype.performDamage.call(this);
    SoundManager.playEnemyDamage();
    this.requestEffect('blink');
};

/* 表现倒下（死亡后的消失效果） */
Game_Enemy.prototype.performCollapse = function() {
    Game_Battler.prototype.performCollapse.call(this);
    switch (this.collapseType()) {
    case 0:
        this.requestEffect('collapse');
        SoundManager.playEnemyCollapse();
        break;
    case 1:
        this.requestEffect('bossCollapse');
        SoundManager.playBossCollapse1();
        break;
    case 2:
        this.requestEffect('instantCollapse');
        break;
    }
};

/* 变身 */
Game_Enemy.prototype.transform = function(enemyId) {
    var name = this.originalName();
    this._enemyId = enemyId;
    if (this.originalName() !== name) {
        this._letter = '';
        this._plural = false;
    }
    this.refresh();
    if (this.numActions() &gt; 0) {
        this.makeActions();
    }
};

/* 是否符合条件 */
Game_Enemy.prototype.meetsCondition = function(action) {
    var param1 = action.conditionParam1;
    var param2 = action.conditionParam2;
    switch (action.conditionType) {
    case 1:
        return this.meetsTurnCondition(param1, param2);
    case 2:
        return this.meetsHpCondition(param1, param2);
    case 3:
        return this.meetsMpCondition(param1, param2);
    case 4:
        return this.meetsStateCondition(param1);
    case 5:
        return this.meetsPartyLevelCondition(param1);
    case 6:
        return this.meetsSwitchCondition(param1);
    default:
        return true;
    }
};

/* 是否符合回合条件 */
Game_Enemy.prototype.meetsTurnCondition = function(param1, param2) {
    var n = $gameTroop.turnCount();
    if (param2 === 0) {
        return n === param1;
    } else {
        return n &gt; 0 &amp;&amp; n &gt;= param1 &amp;&amp; n % param2 === param1 % param2;
    }
};

/* 是否符合 HP 条件 */
Game_Enemy.prototype.meetsHpCondition = function(param1, param2) {
    return this.hpRate() &gt;= param1 &amp;&amp; this.hpRate() &lt;= param2;
};

/* 是否符合 MP 条件 */
Game_Enemy.prototype.meetsMpCondition = function(param1, param2) {
    return this.mpRate() &gt;= param1 &amp;&amp; this.mpRate() &lt;= param2;
};

/* 是否符合状态条件 */
Game_Enemy.prototype.meetsStateCondition = function(param) {
    return this.isStateAffected(param);
};

/* 是否符合队伍等级条件 */
Game_Enemy.prototype.meetsPartyLevelCondition = function(param) {
    return $gameParty.highestLevel() &gt;= param;
};

/* 是否符合开关条件 */
Game_Enemy.prototype.meetsSwitchCondition = function(param) {
    return $gameSwitches.value(param);
};

/* 是否有效的行动 */
Game_Enemy.prototype.isActionValid = function(action) {
    return this.meetsCondition(action) &amp;&amp; this.canUse($dataSkills[action.skillId]);
};

/* 选择行动 */
Game_Enemy.prototype.selectAction = function(actionList, ratingZero) {
    var sum = actionList.reduce(function(r, a) {
        return r + a.rating - ratingZero;
    }, 0);
    if (sum &gt; 0) {
        var value = Math.randomInt(sum);
        for (var i = 0; i &lt; actionList.length; i) {
            var action = actionList[i];
            value -= action.rating - ratingZero;
            if (value &lt; 0) {
                return action;
            }
        }
    } else {
        return null;
    }
};

/* 选择所有行动 */
Game_Enemy.prototype.selectAllActions = function(actionList) {
    var ratingMax = Math.max.apply(null, actionList.map(function(a) {
        return a.rating;
    }));
    var ratingZero = ratingMax - 3;
    actionList = actionList.filter(function(a) {
        return a.rating &gt; ratingZero;
    });
    for (var i = 0; i &lt; this.numActions(); i) {
        this.action(i).setEnemyAction(this.selectAction(actionList, ratingZero));
    }
};

/* 制作行动 */
Game_Enemy.prototype.makeActions = function() {
    Game_Battler.prototype.makeActions.call(this);
    if (this.numActions() &gt; 0) {
        var actionList = this.enemy().actions.filter(function(a) {
            return this.isActionValid(a);
        }, this);
        if (actionList.length &gt; 0) {
            this.selectAllActions(actionList);
        }
    }
    this.setActionState('waiting');
};

//-----------------------------------------------------------------------------
// 游戏_角色们
// Game_Actors
//
// 角色数组的封装类。
// The wrapper class for an actor array.

function Game_Actors() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_Actors.prototype.initialize = function() {
    this._data = [];
};

/* 角色 */
Game_Actors.prototype.actor = function(actorId) {
    if ($dataActors[actorId]) {
        if (!this._data[actorId]) {
            this._data[actorId] = new Game_Actor(actorId);
        }
        return this._data[actorId];
    }
    return null;
};

//-----------------------------------------------------------------------------
// 游戏_单位
// Game_Unit
// 
// Game_Party 和 Game_Troop 的父类。
// The superclass of Game_Party and Game_Troop.

function Game_Unit() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_Unit.prototype.initialize = function() {
    this._inBattle = false;
};

/* 是否在战斗中 */
Game_Unit.prototype.inBattle = function() {
    return this._inBattle;
};

/* 成员 */
Game_Unit.prototype.members = function() {
    return [];
};

/* 活着的成员 */
Game_Unit.prototype.aliveMembers = function() {
    return this.members().filter(function(member) {
        return member.isAlive();
    });
};

/* 死亡的成员 */
Game_Unit.prototype.deadMembers = function() {
    return this.members().filter(function(member) {
        return member.isDead();
    });
};

/* 可移动的成员 */
Game_Unit.prototype.movableMembers = function() {
    return this.members().filter(function(member) {
        return member.canMove();
    });
};

/* 清除行动 */
Game_Unit.prototype.clearActions = function() {
    return this.members().forEach(function(member) {
        return member.clearActions();
    });
};

/* 敏捷 */
Game_Unit.prototype.agility = function() {
    var members = this.members();
    if (members.length === 0) {
        return 1;
    }
    var sum = members.reduce(function(r, member) {
        return r + member.agi;
    }, 0);
    return sum / members.length;
};

/* 受到攻击几率总和 */
Game_Unit.prototype.tgrSum = function() {
    return this.aliveMembers().reduce(function(r, member) {
        return r + member.tgr;
    }, 0);
};

/* 随机目标 */
Game_Unit.prototype.randomTarget = function() {
    var tgrRand = Math.random() * this.tgrSum();
    var target = null;
    this.aliveMembers().forEach(function(member) {
        tgrRand -= member.tgr;
        if (tgrRand &lt;= 0 &amp;&amp; !target) {
            target = member;
        }
    });
    return target;
};

/* 随机死亡目标 */
Game_Unit.prototype.randomDeadTarget = function() {
    var members = this.deadMembers();
    if (members.length === 0) {
        return null;
    }
    return members[Math.floor(Math.random() * members.length)];
};

/* 顺利获取目标 
 * 返回指定索引的目标，当索引对应的目标无效时返回存活队员的首个对象。
 * PS：smooth 应该是指就算 index 有问题也能顺利返回一个目标。
 */
Game_Unit.prototype.smoothTarget = function(index) {
    if (index &lt; 0) {
        index = 0;
    }
    var member = this.members()[index];
    return (member &amp;&amp; member.isAlive()) ? member : this.aliveMembers()[0];
};

/* 顺利获取死亡目标 */
Game_Unit.prototype.smoothDeadTarget = function(index) {
    if (index &lt; 0) {
        index = 0;
    }
    var member = this.members()[index];
    return (member &amp;&amp; member.isDead()) ? member : this.deadMembers()[0];
};

/* 清除结果 */
Game_Unit.prototype.clearResults = function() {
    this.members().forEach(function(member) {
        member.clearResult();
    });
};

/* 当战斗开始 */
Game_Unit.prototype.onBattleStart = function() {
    this.members().forEach(function(member) {
        member.onBattleStart();
    });
    this._inBattle = true;
};

/* 当战斗结束 */
Game_Unit.prototype.onBattleEnd = function() {
    this._inBattle = false;
    this.members().forEach(function(member) {
        member.onBattleEnd();
    });
};

/* 制作行动 */
Game_Unit.prototype.makeActions = function() {
    this.members().forEach(function(member) {
        member.makeActions();
    });
};

/* 选择 */
Game_Unit.prototype.select = function(activeMember) {
    this.members().forEach(function(member) {
        if (member === activeMember) {
            member.select();
        } else {
            member.deselect();
        }
    });
};

/* 是否全部死亡 */
Game_Unit.prototype.isAllDead = function() {
    return this.aliveMembers().length === 0;
};

/* 掩护的战斗者 */
Game_Unit.prototype.substituteBattler = function() {
    var members = this.members();
    for (var i = 0; i &lt; members.length; i) {
        if (members[i].isSubstitute()) {
            return members[i];
        }
    }
};

//-----------------------------------------------------------------------------
// 游戏_队伍
// Game_Party
//
// 队伍的游戏对象类。包括金钱和物品等信息。
// The game object class for the party. Information such as gold and items is
// included.

function Game_Party() {
    this.initialize.apply(this, arguments);
}

Game_Party.prototype = Object.create(Game_Unit.prototype);
Game_Party.prototype.constructor = Game_Party;

Game_Party.ABILITY_ENCOUNTER_HALF    = 0;  // 队伍能力-遇敌减半 
Game_Party.ABILITY_ENCOUNTER_NONE    = 1;  // 队伍能力-无遇敌 
Game_Party.ABILITY_CANCEL_SURPRISE   = 2;  // 队伍能力-取消偷袭 
Game_Party.ABILITY_RAISE_PREEMPTIVE  = 3;  // 队伍能力-增加先发制人率 
Game_Party.ABILITY_GOLD_DOUBLE       = 4;  // 队伍能力-双倍金钱 
Game_Party.ABILITY_DROP_ITEM_DOUBLE  = 5;  // 队伍能力-双倍掉落物品 

/* 初始化 */
Game_Party.prototype.initialize = function() {
    Game_Unit.prototype.initialize.call(this);
    this._gold = 0;
    this._steps = 0;
    this._lastItem = new Game_Item();
    this._menuActorId = 0;
    this._targetActorId = 0;
    this._actors = [];
    this.initAllItems();
};

/* 初始化所有物品 */
Game_Party.prototype.initAllItems = function() {
    this._items = {};
    this._weapons = {};
    this._armors = {};
};

/* 是否存在角色 */
Game_Party.prototype.exists = function() {
    return this._actors.length &gt; 0;
};

/* 大小 */
Game_Party.prototype.size = function() {
    return this.members().length;
};

/* 是否为空 */
Game_Party.prototype.isEmpty = function() {
    return this.size() === 0;
};

/* 成员 */
Game_Party.prototype.members = function() {
    return this.inBattle() ? this.battleMembers() : this.allMembers();
};

/* 所有成员 */
Game_Party.prototype.allMembers = function() {
    return this._actors.map(function(id) {
        return $gameActors.actor(id);
    });
};

/* 战斗成员 */
Game_Party.prototype.battleMembers = function() {
    return this.allMembers().slice(0, this.maxBattleMembers()).filter(function(actor) {
        return actor.isAppeared();
    });
};

/* 最大战斗成员数 */
Game_Party.prototype.maxBattleMembers = function() {
    return 4;
};

/* 队长 */
Game_Party.prototype.leader = function() {
    return this.battleMembers()[0];
};

/* 复活战斗成员 
 * 允许战斗失败的情况下，战斗失败后全员复活且 1 血。
 */
Game_Party.prototype.reviveBattleMembers = function() {
    this.battleMembers().forEach(function(actor) {
        if (actor.isDead()) {
            actor.setHp(1);
        }
    });
};

/* 物品 */
Game_Party.prototype.items = function() {
    var list = [];
    for (var id in this._items) {
        list.push($dataItems[id]);
    }
    return list;
};

/* 武器 */
Game_Party.prototype.weapons = function() {
    var list = [];
    for (var id in this._weapons) {
        list.push($dataWeapons[id]);
    }
    return list;
};

/* 护甲 */
Game_Party.prototype.armors = function() {
    var list = [];
    for (var id in this._armors) {
        list.push($dataArmors[id]);
    }
    return list;
};

/* 装备物品（武器和护甲） */
Game_Party.prototype.equipItems = function() {
    return this.weapons().concat(this.armors());
};

/* 所有物品（物品、武器和护甲） */
Game_Party.prototype.allItems = function() {
    return this.items().concat(this.equipItems());
};

/* 物品容器 */
Game_Party.prototype.itemContainer = function(item) {
    if (!item) {
        return null;
    } else if (DataManager.isItem(item)) {
        return this._items;
    } else if (DataManager.isWeapon(item)) {
        return this._weapons;
    } else if (DataManager.isArmor(item)) {
        return this._armors;
    } else {
        return null;
    }
};

/* 设置初始成员 */
Game_Party.prototype.setupStartingMembers = function() {
    this._actors = [];
    $dataSystem.partyMembers.forEach(function(actorId) {
        if ($gameActors.actor(actorId)) {
            this._actors.push(actorId);
        }
    }, this);
};

/* 名字 */
Game_Party.prototype.name = function() {
    var numBattleMembers = this.battleMembers().length;
    if (numBattleMembers === 0) {
        return '';
    } else if (numBattleMembers === 1) {
        return this.leader().name();
    } else {
        return TextManager.partyName.format(this.leader().name());
    }
};

/* 设置战斗测试 */
Game_Party.prototype.setupBattleTest = function() {
    this.setupBattleTestMembers();
    this.setupBattleTestItems();
};

/* 设置战斗测试成员 */
Game_Party.prototype.setupBattleTestMembers = function() {
    $dataSystem.testBattlers.forEach(function(battler) {
        var actor = $gameActors.actor(battler.actorId);
        if (actor) {
            actor.changeLevel(battler.level, false);
            actor.initEquips(battler.equips);
            actor.recoverAll();
            this.addActor(battler.actorId);
        }
    }, this);
};

/* 设置战斗测试物品 */
Game_Party.prototype.setupBattleTestItems = function() {
    $dataItems.forEach(function(item) {
        if (item &amp;&amp; item.name.length &gt; 0) {
            this.gainItem(item, this.maxItems(item));
        }
    }, this);
};

/* 最高的等级
 * 返回队伍中等级最高的成员的等级。
 */
Game_Party.prototype.highestLevel = function() {
    return Math.max.apply(null, this.members().map(function(actor) {
        return actor.level;
    }));
};

/* 添加角色 */
Game_Party.prototype.addActor = function(actorId) {
    if (!this._actors.contains(actorId)) {
        this._actors.push(actorId);
        $gamePlayer.refresh();
        $gameMap.requestRefresh();
    }
};

/* 移除角色 */
Game_Party.prototype.removeActor = function(actorId) {
    if (this._actors.contains(actorId)) {
        this._actors.splice(this._actors.indexOf(actorId), 1);
        $gamePlayer.refresh();
        $gameMap.requestRefresh();
    }
};

/* 金钱 */
Game_Party.prototype.gold = function() {
    return this._gold;
};

/* 获得金钱 */
Game_Party.prototype.gainGold = function(amount) {
    this._gold = (this._gold + amount).clamp(0, this.maxGold());
};

/* 失去金钱 */
Game_Party.prototype.loseGold = function(amount) {
    this.gainGold(-amount);
};

/* 金钱上限 */
Game_Party.prototype.maxGold = function() {
    return 99999999;
};

/* 步数 */
Game_Party.prototype.steps = function() {
    return this._steps;
};

/* 增加步数 */
Game_Party.prototype.increaseSteps = function() {
    this._steps;
};

/* 物品数量 */
Game_Party.prototype.numItems = function(item) {
    var container = this.itemContainer(item);
    return container ? container[item.id] || 0 : 0;
};

/* 物品上限 */
Game_Party.prototype.maxItems = function(item) {
    return 99;
};

/* 是否该物品数量超过上限*/
Game_Party.prototype.hasMaxItems = function(item) {
    return this.numItems(item) &gt;= this.maxItems(item);
};

/* 是否拥有该物品 */
Game_Party.prototype.hasItem = function(item, includeEquip) {
    if (includeEquip === undefined) {
        includeEquip = false;
    }
    if (this.numItems(item) &gt; 0) {
        return true;
    } else if (includeEquip &amp;&amp; this.isAnyMemberEquipped(item)) {
        return true;
    } else {
        return false;
    }
};

/* 是否所有成员装备该物品 */
Game_Party.prototype.isAnyMemberEquipped = function(item) {
    return this.members().some(function(actor) {
        return actor.equips().contains(item);
    });
};

/* 获得物品 */
Game_Party.prototype.gainItem = function(item, amount, includeEquip) {
    var container = this.itemContainer(item);
    if (container) {
        var lastNumber = this.numItems(item);
        var newNumber = lastNumber + amount;
        container[item.id] = newNumber.clamp(0, this.maxItems(item));
        if (container[item.id] === 0) {
            delete container[item.id];
        }
        if (includeEquip &amp;&amp; newNumber &lt; 0) {
            this.discardMembersEquip(item, -newNumber);
        }
        $gameMap.requestRefresh();
    }
};

/* 丢弃成员装备 */
Game_Party.prototype.discardMembersEquip = function(item, amount) {
    var n = amount;
    this.members().forEach(function(actor) {
        while (n &gt; 0 &amp;&amp; actor.isEquipped(item)) {
            actor.discardEquip(item);
            n--;
        }
    });
};

/* 失去物品 */
Game_Party.prototype.loseItem = function(item, amount, includeEquip) {
    this.gainItem(item, -amount, includeEquip);
};

/* 消耗物品 */
Game_Party.prototype.consumeItem = function(item) {
    if (DataManager.isItem(item) &amp;&amp; item.consumable) {
        this.loseItem(item, 1);
    }
};

/* 是否可使用 */
Game_Party.prototype.canUse = function(item) {
    return this.members().some(function(actor) {
        return actor.canUse(item);
    });
};

/* 是否可输入 */
Game_Party.prototype.canInput = function() {
    return this.members().some(function(actor) {
        return actor.canInput();
    });
};

/* 是否全死亡 */
Game_Party.prototype.isAllDead = function() {
    if (Game_Unit.prototype.isAllDead.call(this)) {
        return this.inBattle() || !this.isEmpty();
    } else {
        return false;
    }
};

/* 当玩家行走 */
Game_Party.prototype.onPlayerWalk = function() {
    this.members().forEach(function(actor) {
        return actor.onPlayerWalk();
    });
};

/* 菜单角色
 * 菜单界面中选中的角色。
 */
Game_Party.prototype.menuActor = function() {
    var actor = $gameActors.actor(this._menuActorId);
    if (!this.members().contains(actor)) {
        actor = this.members()[0];
    }
    return actor;
};

/* 设置菜单角色  
 * 设置菜单界面中选中的角色。
 */
Game_Party.prototype.setMenuActor = function(actor) {
    this._menuActorId = actor.actorId();
};

/* 制作下一个菜单角色 
 * 技能、装备和状态界面按 PageDown 后切换下一个角色。
 */
Game_Party.prototype.makeMenuActorNext = function() {
    var index = this.members().indexOf(this.menuActor());
    if (index &gt;= 0) {
        index = (index + 1) % this.members().length;
        this.setMenuActor(this.members()[index]);
    } else {
        this.setMenuActor(this.members()[0]);
    }
};

/* 制作上一个菜单角色 
 * 技能、装备和状态界面按 PageUp 后切换上一个角色。
 */
Game_Party.prototype.makeMenuActorPrevious = function() {
    var index = this.members().indexOf(this.menuActor());
    if (index &gt;= 0) {
        index = (index + this.members().length - 1) % this.members().length;
        this.setMenuActor(this.members()[index]);
    } else {
        this.setMenuActor(this.members()[0]);
    }
};

/* 目标角色 */
Game_Party.prototype.targetActor = function() {
    var actor = $gameActors.actor(this._targetActorId);
    if (!this.members().contains(actor)) {
        actor = this.members()[0];
    }
    return actor;
};

/* 设置目标角色 */
Game_Party.prototype.setTargetActor = function(actor) {
    this._targetActorId = actor.actorId();
};

/* 上个项目 */
Game_Party.prototype.lastItem = function() {
    return this._lastItem.object();
};

/* 设置上个项目 */
Game_Party.prototype.setLastItem = function(item) {
    this._lastItem.setObject(item);
};

/* 交换顺序 */
Game_Party.prototype.swapOrder = function(index1, index2) {
    var temp = this._actors[index1];
    this._actors[index1] = this._actors[index2];
    this._actors[index2] = temp;
    $gamePlayer.refresh();
};

/* 存档的人物行走图 */
Game_Party.prototype.charactersForSavefile = function() {
    return this.battleMembers().map(function(actor) {
        return [actor.characterName(), actor.characterIndex()];
    });
};

/* 存档的脸图 */
Game_Party.prototype.facesForSavefile = function() {
    return this.battleMembers().map(function(actor) {
        return [actor.faceName(), actor.faceIndex()];
    });
};

/* 队伍能力 */
Game_Party.prototype.partyAbility = function(abilityId) {
    return this.battleMembers().some(function(actor) {
        return actor.partyAbility(abilityId);
    });
};

/* 是否遇敌减半 */
Game_Party.prototype.hasEncounterHalf = function() {
    return this.partyAbility(Game_Party.ABILITY_ENCOUNTER_HALF);
};

/* 是否无遇敌 */
Game_Party.prototype.hasEncounterNone = function() {
    return this.partyAbility(Game_Party.ABILITY_ENCOUNTER_NONE);
};

/* 是否取消偷袭 */
Game_Party.prototype.hasCancelSurprise = function() {
    return this.partyAbility(Game_Party.ABILITY_CANCEL_SURPRISE);
};

/* 是否增加先发制人率 */
Game_Party.prototype.hasRaisePreemptive = function() {
    return this.partyAbility(Game_Party.ABILITY_RAISE_PREEMPTIVE);
};

/* 是否双倍金钱 */
Game_Party.prototype.hasGoldDouble = function() {
    return this.partyAbility(Game_Party.ABILITY_GOLD_DOUBLE);
};

/* 是否双倍掉落物品 */
Game_Party.prototype.hasDropItemDouble = function() {
    return this.partyAbility(Game_Party.ABILITY_DROP_ITEM_DOUBLE);
};

/* 先发制人概率 */
Game_Party.prototype.ratePreemptive = function(troopAgi) {
    var rate = this.agility() &gt;= troopAgi ? 0.05 : 0.03;
    if (this.hasRaisePreemptive()) {
        rate *= 4;
    }
    return rate;
};

/* 偷袭概率 */
Game_Party.prototype.rateSurprise = function(troopAgi) {
    var rate = this.agility() &gt;= troopAgi ? 0.03 : 0.05;
    if (this.hasCancelSurprise()) {
        rate = 0;
    }
    return rate;
};

/* 表现胜利 */
Game_Party.prototype.performVictory = function() {
    this.members().forEach(function(actor) {
        actor.performVictory();
    });
};

/* 表现逃跑 */
Game_Party.prototype.performEscape = function() {
    this.members().forEach(function(actor) {
        actor.performEscape();
    });
};

/* 移除战斗状态 */
Game_Party.prototype.removeBattleStates = function() {
    this.members().forEach(function(actor) {
        actor.removeBattleStates();
    });
};

/* 请求动作刷新 */
Game_Party.prototype.requestMotionRefresh = function() {
    this.members().forEach(function(actor) {
        actor.requestMotionRefresh();
    });
};

//-----------------------------------------------------------------------------
// 游戏_敌群 
// Game_Troop
//
// 敌群和战斗相关数据的游戏对象类。 
// The game object class for a troop and the battle-related data.

function Game_Troop() {
    this.initialize.apply(this, arguments);
}

Game_Troop.prototype = Object.create(Game_Unit.prototype);
Game_Troop.prototype.constructor = Game_Troop;

Game_Troop.LETTER_TABLE_HALF = [
    ' A',' B',' C',' D',' E',' F',' G',' H',' I',' J',' K',' L',' M',
    ' N',' O',' P',' Q',' R',' S',' T',' U',' V',' W',' X',' Y',' Z'
];  // 半角字母表 
Game_Troop.LETTER_TABLE_FULL = [
    'Ａ','Ｂ','Ｃ','Ｄ','Ｅ','Ｆ','Ｇ','Ｈ','Ｉ','Ｊ','Ｋ','Ｌ','Ｍ',
    'Ｎ','Ｏ','Ｐ','Ｑ','Ｒ','Ｓ','Ｔ','Ｕ','Ｖ','Ｗ','Ｘ','Ｙ','Ｚ'
];  // 全角字母表 

/* 初始化 */
Game_Troop.prototype.initialize = function() {
    Game_Unit.prototype.initialize.call(this);
    this._interpreter = new Game_Interpreter();
    this.clear();
};

/* 是否事件运行中 */
Game_Troop.prototype.isEventRunning = function() {
    return this._interpreter.isRunning();
};

/* 更新解释器 */
Game_Troop.prototype.updateInterpreter = function() {
    this._interpreter.update();
};

/* 回合计数 */
Game_Troop.prototype.turnCount = function() {
    return this._turnCount;
};

/* 成员 */
Game_Troop.prototype.members = function() {
    return this._enemies;
};

/* 清除 */
Game_Troop.prototype.clear = function() {
    this._interpreter.clear();
    this._troopId = 0;
    this._eventFlags = {};
    this._enemies = [];
    this._turnCount = 0;
    this._namesCount = {};
};

/* 敌群 */
Game_Troop.prototype.troop = function() {
    return $dataTroops[this._troopId];
};

/* 设置 */
Game_Troop.prototype.setup = function(troopId) {
    this.clear();
    this._troopId = troopId;
    this._enemies = [];
    this.troop().members.forEach(function(member) {
        if ($dataEnemies[member.enemyId]) {
            var enemyId = member.enemyId;
            var x = member.x;
            var y = member.y;
            var enemy = new Game_Enemy(enemyId, x, y);
            if (member.hidden) {
                enemy.hide();
            }
            this._enemies.push(enemy);
        }
    }, this);
    this.makeUniqueNames();
};

/* 制作唯一的名称 */
Game_Troop.prototype.makeUniqueNames = function() {
    var table = this.letterTable();
    this.members().forEach(function(enemy) {
        if (enemy.isAlive() &amp;&amp; enemy.isLetterEmpty()) {
            var name = enemy.originalName();
            var n = this._namesCount[name] || 0;
            enemy.setLetter(table[n % table.length]);
            this._namesCount[name] = n + 1;
        }
    }, this);
    this.members().forEach(function(enemy) {
        var name = enemy.originalName();
        if (this._namesCount[name] &gt;= 2) {
            enemy.setPlural(true);
        }
    }, this);
};

/* 字母表 */
Game_Troop.prototype.letterTable = function() {
    return $gameSystem.isCJK() ? Game_Troop.LETTER_TABLE_FULL :
            Game_Troop.LETTER_TABLE_HALF;
};

/* 敌人名称 */
Game_Troop.prototype.enemyNames = function() {
    var names = [];
    this.members().forEach(function(enemy) {
        var name = enemy.originalName();
        if (enemy.isAlive() &amp;&amp; !names.contains(name)) {
            names.push(name);
        }
    });
    return names;
};

/* 是否满足条件 */
Game_Troop.prototype.meetsConditions = function(page) {
    var c = page.conditions;
    if (!c.turnEnding &amp;&amp; !c.turnValid &amp;&amp; !c.enemyValid &amp;&amp;
            !c.actorValid &amp;&amp; !c.switchValid) {
        return false;  // Conditions not set
    }
    if (c.turnEnding) {
        if (!BattleManager.isTurnEnd()) {
            return false;
        }
    }
    if (c.turnValid) {
        var n = this._turnCount;
        var a = c.turnA;
        var b = c.turnB;
        if ((b === 0 &amp;&amp; n !== a)) {
            return false;
        }
        if ((b &gt; 0 &amp;&amp; (n &lt; 1 || n &lt; a || n % b !== a % b))) {
            return false;
        }
    }
    if (c.enemyValid) {
        var enemy = $gameTroop.members()[c.enemyIndex];
        if (!enemy || enemy.hpRate() * 100 &gt; c.enemyHp) {
            return false;
        }
    }
    if (c.actorValid) {
        var actor = $gameActors.actor(c.actorId);
        if (!actor || actor.hpRate() * 100 &gt; c.actorHp) {
            return false;
        }
    }
    if (c.switchValid) {
        if (!$gameSwitches.value(c.switchId)) {
            return false;
        }
    }
    return true;
};

/* 设置战斗事件 */
Game_Troop.prototype.setupBattleEvent = function() {
    if (!this._interpreter.isRunning()) {
        if (this._interpreter.setupReservedCommonEvent()) {
            return;
        }
        var pages = this.troop().pages;
        for (var i = 0; i &lt; pages.length; i) {
            var page = pages[i];
            if (this.meetsConditions(page) &amp;&amp; !this._eventFlags[i]) {
                this._interpreter.setup(page.list);
                if (page.span &lt;= 1) {
                    this._eventFlags[i] = true;
                }
                break;
            }
        }
    }
};

/* 增加回合 */
Game_Troop.prototype.increaseTurn = function() {
    var pages = this.troop().pages;
    for (var i = 0; i &lt; pages.length; i) {
        var page = pages[i];
        if (page.span === 1) {
            this._eventFlags[i] = false;
        }
    }
    this._turnCount;
};

/* 总经验 */
Game_Troop.prototype.expTotal = function() {
    return this.deadMembers().reduce(function(r, enemy) {
        return r + enemy.exp();
    }, 0);
};

/* 总金钱 */
Game_Troop.prototype.goldTotal = function() {
    return this.deadMembers().reduce(function(r, enemy) {
        return r + enemy.gold();
    }, 0) * this.goldRate();
};

/* 金钱倍率 */
Game_Troop.prototype.goldRate = function() {
    return $gameParty.hasGoldDouble() ? 2 : 1;
};

/* 制作掉落物品 */
Game_Troop.prototype.makeDropItems = function() {
    return this.deadMembers().reduce(function(r, enemy) {
        return r.concat(enemy.makeDropItems());
    }, []);
};

//-----------------------------------------------------------------------------
// 游戏_地图
// Game_Map
//
// 地图的游戏对象类。它包含滚动和通行决定功能。
// The game object class for a map. It contains scrolling and passage
// determination functions.
//
// PS：以下翻译，位置(x,y)是以图块为单位的，坐标(x,y)是以像素为单位的。

function Game_Map() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_Map.prototype.initialize = function() {
    this._interpreter = new Game_Interpreter();
    this._mapId = 0;
    this._tilesetId = 0;
    this._events = [];
    this._commonEvents = [];
    this._vehicles = [];
    this._displayX = 0;
    this._displayY = 0;
    this._nameDisplay = true;
    this._scrollDirection = 2;
    this._scrollRest = 0;
    this._scrollSpeed = 4;
    this._parallaxName = '';
    this._parallaxZero = false;
    this._parallaxLoopX = false;
    this._parallaxLoopY = false;
    this._parallaxSx = 0;
    this._parallaxSy = 0;
    this._parallaxX = 0;
    this._parallaxY = 0;
    this._battleback1Name = null;
    this._battleback2Name = null;
    this.createVehicles();
};

/* 设置 */
Game_Map.prototype.setup = function(mapId) {
    if (!$dataMap) {
        throw new Error('The map data is not available');
    }
    this._mapId = mapId;
    this._tilesetId = $dataMap.tilesetId;
    this._displayX = 0;
    this._displayY = 0;
    this.refereshVehicles();
    this.setupEvents();
    this.setupScroll();
    this.setupParallax();
    this.setupBattleback();
    this._needsRefresh = false;
};

/* 是否事件运行中 */
Game_Map.prototype.isEventRunning = function() {
    return this._interpreter.isRunning() || this.isAnyEventStarting();
};

/* 图块宽 */
Game_Map.prototype.tileWidth = function() {
    return 48;
};

/* 图块高 */
Game_Map.prototype.tileHeight = function() {
    return 48;
};

/* 地图 ID */
Game_Map.prototype.mapId = function() {
    return this._mapId;
};

/* 图块组 ID */
Game_Map.prototype.tilesetId = function() {
    return this._tilesetId;
};

/* 显示的 X 位置 */
Game_Map.prototype.displayX = function() {
    return this._displayX;
};

/* 显示的 Y 位置 */
Game_Map.prototype.displayY = function() {
    return this._displayY;
};

/* 远景名称 */
Game_Map.prototype.parallaxName = function() {
    return this._parallaxName;
};

/* 战斗背景 1 名称 */
Game_Map.prototype.battleback1Name = function() {
    return this._battleback1Name;
};

/* 战斗背景 2 名称 */
Game_Map.prototype.battleback2Name = function() {
    return this._battleback2Name;
};

/* 请求刷新 */
Game_Map.prototype.requestRefresh = function(mapId) {
    this._needsRefresh = true;
};

/* 是否名称显示启用 */
Game_Map.prototype.isNameDisplayEnabled = function() {
    return this._nameDisplay;
};

/* 禁用名称显示 */
Game_Map.prototype.disableNameDisplay = function() {
    this._nameDisplay = false;
};

/* 启用名称显示 */
Game_Map.prototype.enableNameDisplay = function() {
    this._nameDisplay = true;
};

/* 创建载具 */
Game_Map.prototype.createVehicles = function() {
    this._vehicles = [];
    this._vehicles[0] = new Game_Vehicle('boat');
    this._vehicles[1] = new Game_Vehicle('ship');
    this._vehicles[2] = new Game_Vehicle('airship');
};

/* 刷新载具 */
Game_Map.prototype.refereshVehicles = function() {
    this._vehicles.forEach(function(vehicle) {
        vehicle.refresh();
    });
};

/* 载具数组 
 * 返回载具的数组。
 */
Game_Map.prototype.vehicles = function() {
    return this._vehicles;
};

/* 载具 
 * 返回该类型对应的载具的对象。
 */
Game_Map.prototype.vehicle = function(type) {
    if (type ===  0 || type === 'boat') {
        return this.boat();
    } else if (type ===  1 || type === 'ship') {
        return this.ship();
    } else if (type ===  2 || type === 'airship') {
        return this.airship();
    } else {
        return null;
    }
};

/* 小舟 */
Game_Map.prototype.boat = function() {
    return this._vehicles[0];
};

/* 大船 */
Game_Map.prototype.ship = function() {
    return this._vehicles[1];
};

/* 飞艇 */
Game_Map.prototype.airship = function() {
    return this._vehicles[2];
};

/* 设置事件 */
Game_Map.prototype.setupEvents = function() {
    this._events = [];
    for (var i = 0; i &lt; $dataMap.events.length; i) {
        if ($dataMap.events[i]) {
            this._events[i] = new Game_Event(this._mapId, i);
        }
    }
    this._commonEvents = this.parallelCommonEvents().map(function(commonEvent) {
        return new Game_CommonEvent(commonEvent.id);
    });
    this.refreshTileEvents();
};

/* 事件数组 
 * 返回数组元素对象非空的事件数组。
 */
Game_Map.prototype.events = function() {
    return this._events.filter(function(event) {
        return !!event;
    });
};

/* 事件 
 * 返回事件 ID 所对应的事件对象。
 */
Game_Map.prototype.event = function(eventId) {
    return this._events[eventId];
};

/* 消除事件 */
Game_Map.prototype.eraseEvent = function(eventId) {
    this._events[eventId].erase();
};

/* 是否并行处理的公共事件 */
Game_Map.prototype.parallelCommonEvents = function() {
    return $dataCommonEvents.filter(function(commonEvent) {
        return commonEvent &amp;&amp; commonEvent.trigger === 2;
    });
};

/* 设置滚动 */
Game_Map.prototype.setupScroll = function() {
    this._scrollDirection = 2;
    this._scrollRest = 0;
    this._scrollSpeed = 4;
};

/* 设置远景 */
Game_Map.prototype.setupParallax = function() {
    this._parallaxName = $dataMap.parallaxName || '';
    this._parallaxZero = ImageManager.isZeroParallax(this._parallaxName);
    this._parallaxLoopX = $dataMap.parallaxLoopX;
    this._parallaxLoopY = $dataMap.parallaxLoopY;
    this._parallaxSx = $dataMap.parallaxSx;
    this._parallaxSy = $dataMap.parallaxSy;
    this._parallaxX = 0;
    this._parallaxY = 0;
};

/* 设置战斗背景 */
Game_Map.prototype.setupBattleback = function() {
    if ($dataMap.specifyBattleback) {
        this._battleback1Name = $dataMap.battleback1Name;
        this._battleback2Name = $dataMap.battleback2Name;
    } else {
        this._battleback1Name = null;
        this._battleback2Name = null;
    }
};

/* 设置显示坐标 */
Game_Map.prototype.setDisplayPos = function(x, y) {
    if (this.isLoopHorizontal()) {
        this._displayX = x.mod(this.width());
        this._parallaxX = x;
    } else {
        var endX = this.width() - this.screenTileX();
        this._displayX = endX &lt; 0 ? endX / 2 : x.clamp(0, endX);
        this._parallaxX = this._displayX;
    }
    if (this.isLoopVertical()) {
        this._displayY = y.mod(this.height());
        this._parallaxY = y;
    } else {
        var endY = this.height() - this.screenTileY();
        this._displayY = endY &lt; 0 ? endY / 2 : y.clamp(0, endY);
        this._parallaxY = this._displayY;
    }
};

/* 远景原点 X 坐标 */
Game_Map.prototype.parallaxOx = function() {
    if (this._parallaxZero) {
        return this._parallaxX * this.tileWidth();
    } else if (this._parallaxLoopX) {
        return this._parallaxX * this.tileWidth() / 2;
    } else {
        return 0;
    }
};

/* 远景原点 Y 坐标 */
Game_Map.prototype.parallaxOy = function() {
    if (this._parallaxZero) {
        return this._parallaxY * this.tileHeight();
    } else if (this._parallaxLoopY) {
        return this._parallaxY * this.tileHeight() / 2;
    } else {
        return 0;
    }
};

/* 图块组 */
Game_Map.prototype.tileset = function() {
    return $dataTilesets[this._tilesetId];
};

/* 图块组标志 */
Game_Map.prototype.tilesetFlags = function() {
    var tileset = this.tileset();
    if (tileset) {
        return tileset.flags;
    } else {
        return [];
    }
};

/* 显示名称 */
Game_Map.prototype.displayName = function() {
    return $dataMap.displayName;
};

/* 宽 */
Game_Map.prototype.width = function() {
    return $dataMap.width;
};

/* 高 */
Game_Map.prototype.height = function() {
    return $dataMap.height;
};

/* 数据 */
Game_Map.prototype.data = function() {
    return $dataMap.data;
};

/* 是否横向循环 */
Game_Map.prototype.isLoopHorizontal = function() {
    return $dataMap.scrollType === 2 || $dataMap.scrollType === 3;
};

/* 是否纵向循环 */
Game_Map.prototype.isLoopVertical = function() {
    return $dataMap.scrollType === 1 || $dataMap.scrollType === 3;
};

/* 是否禁止奔跑启用 */
Game_Map.prototype.isDashDisabled = function() {
    return $dataMap.disableDashing;
};

/* 遇敌列表 */
Game_Map.prototype.encounterList = function() {
    return $dataMap.encounterList;
};

/* 遇敌步数 */
Game_Map.prototype.encounterStep = function() {
    return $dataMap.encounterStep;
};

/* 是否主世界 
 * 数据库-图块-基本设置-模式是否为世界类型。
 */
Game_Map.prototype.isOverworld = function() {
    return this.tileset() &amp;&amp; this.tileset().mode === 0;
};

/* 画面 X 轴方向图块数 */
Game_Map.prototype.screenTileX = function() {
    return Graphics.width / this.tileWidth();
};

/* 画面 Y 轴方向图块数 */
Game_Map.prototype.screenTileY = function() {
    return Graphics.height / this.tileHeight();
};

/* 自适应 X 坐标 */
Game_Map.prototype.adjustX = function(x) {
    if (this.isLoopHorizontal() &amp;&amp; x &lt; this._displayX -
            (this.width() - this.screenTileX()) / 2) {
        return x - this._displayX + $dataMap.width;
    } else {
        return x - this._displayX;
    }
};

/* 自适应 Y 坐标 */
Game_Map.prototype.adjustY = function(y) {
    if (this.isLoopVertical() &amp;&amp; y &lt; this._displayY -
            (this.height() - this.screenTileY()) / 2) {
        return y - this._displayY + $dataMap.height;
    } else {
        return y - this._displayY;
    }
};

/* 环形 X 位置 
 * 当横向循环时将位置转换为原地图位置。 假设地图宽为 17 图块时，-1 则为 16，17 则为 0 。
 */
Game_Map.prototype.roundX = function(x) {
    return this.isLoopHorizontal() ? x.mod(this.width()) : x;
};

/* 环形 Y 位置 
 * 当纵向循环时将位置转换为原地图位置。 假设地图高为 13 图块时，-1 则为 12，13 则为 0 。
 */
Game_Map.prototype.roundY = function(y) {
    return this.isLoopVertical() ? y.mod(this.height()) : y;
};

/* 该方向的 X 位置
 * @param {Number} x 在地图上的 X 位置
 * @param {Number} d 移动的方向（4：向左，6：向右） 
 */
Game_Map.prototype.xWithDirection = function(x, d) {
    return x + (d === 6 ? 1 : d === 4 ? -1 : 0);
};

/* 该方向的 Y 位置 
 * @param {Number} y 在地图上的 Y 位置
 * @param {Number} d 移动的方向（2：向下，8：向上） 
 */
Game_Map.prototype.yWithDirection = function(y, d) {
    return y + (d === 2 ? 1 : d === 8 ? -1 : 0);
};

/* 该方向的环形 X 位置 */
Game_Map.prototype.roundXWithDirection = function(x, d) {
    return this.roundX(x + (d === 6 ? 1 : d === 4 ? -1 : 0));
};

/* 该方向的环形 Y 位置 */
Game_Map.prototype.roundYWithDirection = function(y, d) {
    return this.roundY(y + (d === 2 ? 1 : d === 8 ? -1 : 0));
};

/* X 位置差值 */
Game_Map.prototype.deltaX = function(x1, x2) {
    var result = x1 - x2;
    if (this.isLoopHorizontal() &amp;&amp; Math.abs(result) &gt; this.width() / 2) {
        if (result &lt; 0) {
            result += this.width();
        } else {
            result -= this.width();
        }
    }
    return result;
};

/* Y 位置差值 */
Game_Map.prototype.deltaY = function(y1, y2) {
    var result = y1 - y2;
    if (this.isLoopVertical() &amp;&amp; Math.abs(result) &gt; this.height() / 2) {
        if (result &lt; 0) {
            result += this.height();
        } else {
            result -= this.height();
        }
    }
    return result;
};

/* 距离 
 * (x1,y1) 和 (x2,y2) 两点之间的距离。 
 */
Game_Map.prototype.distance = function(x1, y1, x2, y2) {
    return Math.abs(this.deltaX(x1, x2)) + Math.abs(this.deltaY(y1, y2));
};

/* 画布 X 坐标转换到地图 X 位置 */
Game_Map.prototype.canvasToMapX = function(x) {
    var tileWidth = this.tileWidth();
    var originX = this._displayX * tileWidth;
    var mapX = Math.floor((originX + x) / tileWidth);
    return this.roundX(mapX);
};

/* 画布 Y 坐标转换到地图 Y 位置 */
Game_Map.prototype.canvasToMapY = function(y) {
    var tileHeight = this.tileHeight();
    var originY = this._displayY * tileHeight;
    var mapY = Math.floor((originY + y) / tileHeight);
    return this.roundY(mapY);
};

/* 自动播放 */
Game_Map.prototype.autoplay = function() {
    if ($dataMap.autoplayBgm) {
        if ($gamePlayer.isInVehicle()) {
            $gameSystem.saveWalkingBgm2();
        } else {
            AudioManager.playBgm($dataMap.bgm);
        }
    }
    if ($dataMap.autoplayBgs) {
        AudioManager.playBgs($dataMap.bgs);
    }
};

/* 如果需要就刷新 */
Game_Map.prototype.refreshIfNeeded = function() {
    if (this._needsRefresh) {
        this.refresh();
    }
};

/* 刷新 */
Game_Map.prototype.refresh = function() {
    this.events().forEach(function(event) {
        event.refresh();
    });
    this._commonEvents.forEach(function(event) {
        event.refresh();
    });
    this.refreshTileEvents();
    this._needsRefresh = false;
};

/* 刷新图块事件 */
Game_Map.prototype.refreshTileEvents = function() {
    this.tileEvents = this.events().filter(function(event) {
        return event.isTile();
    });
};

/* 位置 X,Y 的事件 */
Game_Map.prototype.eventsXy = function(x, y) {
    return this.events().filter(function(event) {
        return event.pos(x, y);
    });
};

/* 位置 X,Y 不可穿透的事件 */
Game_Map.prototype.eventsXyNt = function(x, y) {
    return this.events().filter(function(event) {
        return event.posNt(x, y);
    });
};

/* 位置 X,Y 不可穿透的图块事件 */
Game_Map.prototype.tileEventsXy = function(x, y) {
    return this.tileEvents.filter(function(event) {
        return event.posNt(x, y);
    });
};

/* 位置 X,Y 的事件 ID */
Game_Map.prototype.eventIdXy = function(x, y) {
    var list = this.eventsXy(x, y);
    return list.length === 0 ? 0 : list[0].eventId();
};

/* 向下滚动 */
Game_Map.prototype.scrollDown = function(distance) {
    if (this.isLoopVertical()) {
        this._displayY += distance;
        this._displayY %= $dataMap.height;
        if (this._parallaxLoopY) {
            this._parallaxY += distance;
        }
    } else if (this.height() &gt;= this.screenTileY()) {
        var lastY = this._displayY;
        this._displayY = Math.min(this._displayY + distance,
            this.height() - this.screenTileY());
        this._parallaxY += this._displayY - lastY;
    }
};

/* 向左滚动 */
Game_Map.prototype.scrollLeft = function(distance) {
    if (this.isLoopHorizontal()) {
        this._displayX += $dataMap.width - distance;
        this._displayX %= $dataMap.width;
        if (this._parallaxLoopX) {
            this._parallaxX -= distance;
        }
    } else if (this.width() &gt;= this.screenTileX()) {
        var lastX = this._displayX;
        this._displayX = Math.max(this._displayX - distance, 0);
        this._parallaxX += this._displayX - lastX;
    }
};

/* 向右滚动 */
Game_Map.prototype.scrollRight = function(distance) {
    if (this.isLoopHorizontal()) {
        this._displayX += distance;
        this._displayX %= $dataMap.width;
        if (this._parallaxLoopX) {
            this._parallaxX += distance;
        }
    } else if (this.width() &gt;= this.screenTileX()) {
        var lastX = this._displayX;
        this._displayX = Math.min(this._displayX + distance,
            this.width() - this.screenTileX());
        this._parallaxX += this._displayX - lastX;
    }
};

/* 向上滚动 */
Game_Map.prototype.scrollUp = function(distance) {
    if (this.isLoopVertical()) {
        this._displayY += $dataMap.height - distance;
        this._displayY %= $dataMap.height;
        if (this._parallaxLoopY) {
            this._parallaxY -= distance;
        }
    } else if (this.height() &gt;= this.screenTileY()) {
        var lastY = this._displayY;
        this._displayY = Math.max(this._displayY - distance, 0);
        this._parallaxY += this._displayY - lastY;
    }
};

/* 是否有效的 */
Game_Map.prototype.isValid = function(x, y) {
    return x &gt;= 0 &amp;&amp; x &lt; this.width() &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; this.height();
};

/* 检测通行 */
Game_Map.prototype.checkPassage = function(x, y, bit) {
    var flags = this.tilesetFlags();
    var tiles = this.allTiles(x, y);
    for (var i = 0; i &lt; tiles.length; i) {
        var flag = flags[tiles[i]];
        if flag &amp; 0x10) !== 0)  // [*] 对通行无影响（No effect on passage）              continue;         if ((flag &amp; bit) === 0)   // [o] 可通行（Passable）              return true;         if ((flag &amp; bit) === bit) // [x] 不可通行（Impassable）              return false;     }     return false; };  /* 图块 ID */ Game_Map.prototype.tileId = function(x, y, z) {     var width = $dataMap.width;     var height = $dataMap.height;     return $dataMap.data[(z * height + y) * width + x] || 0; };  /* 层叠图块  * 地图有 4 个图层，返回该位置所有图层的图块。  */ Game_Map.prototype.layeredTiles = function(x, y) {     var tiles = [];     for (var i = 0; i &lt; 4; i) {
        tiles.push(this.tileId(x, y, 3 - i));
    }
    return tiles;
};

/* 所有图块 
 * 该位置的图块事件加上该位置的层叠图块。
 */
Game_Map.prototype.allTiles = function(x, y) {
    var tiles = this.tileEventsXy(x, y).map(function(event) {
        return event.tileId();
    });
    return tiles.concat(this.layeredTiles(x, y));
};

/* 自动识别图块类型 */
Game_Map.prototype.autotileType = function(x, y, z) {
    var tileId = this.tileId(x, y, z);
    return tileId &gt;= 2048 ? Math.floor((tileId - 2048) / 48) : -1;
};

/* 是否可通行的 */
Game_Map.prototype.isPassable = function(x, y, d) {
    return this.checkPassage(x, y, (1 &lt;&lt; (d / 2 - 1)) &amp; 0x0f);
};

/* 是否小舟可通行 */
Game_Map.prototype.isBoatPassable = function(x, y) {
    return this.checkPassage(x, y, 0x0200);
};

/* 是否大船可通行 */
Game_Map.prototype.isShipPassable = function(x, y) {
    return this.checkPassage(x, y, 0x0400);
};

/* 是否飞艇可通行的陆地 */
Game_Map.prototype.isAirshipLandOk = function(x, y) {
    return this.checkPassage(x, y, 0x0800) &amp;&amp; this.checkPassage(x, y, 0x0f);
};

/* 检测层叠图层标志 */
Game_Map.prototype.checkLayeredTilesFlags = function(x, y, bit) {
    var flags = this.tilesetFlags();
    return this.layeredTiles(x, y).some(function(tileId) {
        return (flags[tileId] &amp; bit) !== 0;
    });
};

/* 是否梯子 */
Game_Map.prototype.isLadder = function(x, y) {
    return this.isValid(x, y) &amp;&amp; this.checkLayeredTilesFlags(x, y, 0x20);
};

/* 是否草木繁茂处 */
Game_Map.prototype.isBush = function(x, y) {
    return this.isValid(x, y) &amp;&amp; this.checkLayeredTilesFlags(x, y, 0x40);
};

/* 是否柜台 */
Game_Map.prototype.isCounter = function(x, y) {
    return this.isValid(x, y) &amp;&amp; this.checkLayeredTilesFlags(x, y, 0x80);
};

/* 是否有害地形 */
Game_Map.prototype.isDamageFloor = function(x, y) {
    return this.isValid(x, y) &amp;&amp; this.checkLayeredTilesFlags(x, y, 0x100);
};

/* 地形标志 */
Game_Map.prototype.terrainTag = function(x, y) {
    if (this.isValid(x, y)) {
        var flags = this.tilesetFlags();
        var tiles = this.layeredTiles(x, y);
        for (var i = 0; i &lt; tiles.length; i) {             var tag = flags[tiles[i]] {
        var lastX = this._displayX;
        var lastY = this._displayY;
        this.doScroll(this._scrollDirection, this.scrollDistance());
        if (this._displayX === lastX &amp;&amp; this._displayY === lastY) {
            this._scrollRest = 0;
        } else {
            this._scrollRest -= this.scrollDistance();
        }
    }
};

/* 滚动距离 */
Game_Map.prototype.scrollDistance = function() {
    return Math.pow(2, this._scrollSpeed) / 256;
};

/* 进行滚动 */
Game_Map.prototype.doScroll = function(direction, distance) {
    switch (direction) {
    case 2:
        this.scrollDown(distance);
        break;
    case 4:
        this.scrollLeft(distance);
        break;
    case 6:
        this.scrollRight(distance);
        break;
    case 8:
        this.scrollUp(distance);
        break;
    }
};

/* 更新事件 */
Game_Map.prototype.updateEvents = function() {
    this.events().forEach(function(event) {
        event.update();
    });
    this._commonEvents.forEach(function(event) {
        event.update();
    });
};

/* 更新载具 */
Game_Map.prototype.updateVehicles = function() {
    this._vehicles.forEach(function(vehicle) {
        vehicle.update();
    });
};

/* 更新远景 */
Game_Map.prototype.updateParallax = function() {
    if (this._parallaxLoopX) {
        this._parallaxX += this._parallaxSx / this.tileWidth() / 2;
    }
    if (this._parallaxLoopY) {
        this._parallaxY += this._parallaxSy / this.tileHeight() / 2;
    }
};

/* 更改图块组 */
Game_Map.prototype.changeTileset = function(tilesetId) {
    this._tilesetId = tilesetId;
    this.refresh();
};

/* 更改战斗背景 */
Game_Map.prototype.changeBattleback = function(battleback1Name, battleback2Name) {
    this._battleback1Name = battleback1Name;
    this._battleback2Name = battleback2Name;
};

/* 更改远景 */
Game_Map.prototype.changeParallax = function(name, loopX, loopY, sx, sy) {
    this._parallaxName = name;
    this._parallaxZero = ImageManager.isZeroParallax(this._parallaxName);
    if (this._parallaxLoopX &amp;&amp; !loopX) {
        this._parallaxX = 0;
    }
    if (this._parallaxLoopY &amp;&amp; !loopY) {
        this._parallaxY = 0;
    }
    this._parallaxLoopX = loopX;
    this._parallaxLoopY = loopY;
    this._parallaxSx = sx;
    this._parallaxSy = sy;
};

/* 更新解释器 */
Game_Map.prototype.updateInterpreter = function() {
    for (;;) {
        this._interpreter.update();
        if (this._interpreter.isRunning()) {
            return;
        }
        if (this._interpreter.eventId() &gt; 0) {
            this.unlockEvent(this._interpreter.eventId());
            this._interpreter.clear();
        }
        if (!this.setupStartingEvent()) {
            return;
        }
    }
};

/* 解锁事件 */
Game_Map.prototype.unlockEvent = function(eventId) {
    if (this._events[eventId]) {
        this._events[eventId].unlock();
    }
};

/* 设置开始的事件 */
Game_Map.prototype.setupStartingEvent = function() {
    this.refreshIfNeeded();
    if (this._interpreter.setupReservedCommonEvent()) {
        return true;
    }
    if (this.setupTestEvent()) {
        return true;
    }
    if (this.setupStartingMapEvent()) {
        return true;
    }
    if (this.setupAutorunCommonEvent()) {
        return true;
    }
    return false;
};

/* 设置测试事件 */
Game_Map.prototype.setupTestEvent = function() {
    if ($testEvent) {
        this._interpreter.setup($testEvent, 0);
        $testEvent = null;
        return true;
    }
    return false;
};

/* 设置开始的地图事件 */
Game_Map.prototype.setupStartingMapEvent = function() {
    var events = this.events();
    for (var i = 0; i &lt; events.length; i) {
        var event = events[i];
        if (event.isStarting()) {
            event.clearStartingFlag();
            this._interpreter.setup(event.list(), event.eventId());
            return true;
        }
    }
    return false;
};

/* 设置自动运行的公共事件 */
Game_Map.prototype.setupAutorunCommonEvent = function() {
    for (var i = 0; i &lt; $dataCommonEvents.length; i) {
        var event = $dataCommonEvents[i];
        if (event &amp;&amp; event.trigger === 1 &amp;&amp; $gameSwitches.value(event.switchId)) {
            this._interpreter.setup(event.list);
            return true;
        }
    }
    return false;
};

/* 是否有事件开始 */
Game_Map.prototype.isAnyEventStarting = function() {
    return this.events().some(function(event) {
        return event.isStarting();
    });
};

//-----------------------------------------------------------------------------
// 游戏_公共事件
// Game_CommonEvent
//
// 公共事件的游戏对象类。它包含运行并行处理事件的功能。
// The game object class for a common event. It contains functionality for
// running parallel process events.

function Game_CommonEvent() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_CommonEvent.prototype.initialize = function(commonEventId) {
    this._commonEventId = commonEventId;
    this.refresh();
};

/* 事件 */
Game_CommonEvent.prototype.event = function() {
    return $dataCommonEvents[this._commonEventId];
};

/* 列表 */
Game_CommonEvent.prototype.list = function() {
    return this.event().list;
};

/* 刷新 */
Game_CommonEvent.prototype.refresh = function() {
    if (this.isActive()) {
        if (!this._interpreter) {
            this._interpreter = new Game_Interpreter();
        }
    } else {
        this._interpreter = null;
    }
};

/* 是否激活 */
Game_CommonEvent.prototype.isActive = function() {
    var event = this.event();
    return event.trigger === 2 &amp;&amp; $gameSwitches.value(event.switchId);
};

/* 更新 */
Game_CommonEvent.prototype.update = function() {
    if (this._interpreter) {
        if (!this._interpreter.isRunning()) {
            this._interpreter.setup(this.list());
        }
        this._interpreter.update();
    }
};

//-----------------------------------------------------------------------------
// 游戏_人物基础 
// Game_CharacterBase
//
// Game_Character 的父类。它处理所有人物共享的基本信息，如坐标和图像。 
// The superclass of Game_Character. It handles basic information, such as
// coordinates and images, shared by all characters.

function Game_CharacterBase() {
    this.initialize.apply(this, arguments);
}

Object.defineProperties(Game_CharacterBase.prototype, {
    x: { get: function() { return this._x; }, configurable: true },
    y: { get: function() { return this._y; }, configurable: true }
});

/* 初始化 */
Game_CharacterBase.prototype.initialize = function() {
    this.initMembers();
};

/* 初始化成员 */
Game_CharacterBase.prototype.initMembers = function() {
    this._x = 0;
    this._y = 0;
    this._realX = 0;
    this._realY = 0;
    this._moveSpeed = 4;
    this._moveFrequency = 6;
    this._opacity = 255;
    this._blendMode = 0;
    this._direction = 2;
    this._pattern = 1;
    this._priorityType = 1;
    this._tileId = 0;
    this._characterName = '';
    this._characterIndex = 0;
    this._isObjectCharacter = false;
    this._walkAnime = true;
    this._stepAnime = false;
    this._directionFix = false;
    this._through = false;
    this._transparent = false;
    this._bushDepth = 0;
    this._animationId = 0;
    this._balloonId = 0;
    this._animationPlaying = false;
    this._balloonPlaying = false;
    this._animationCount = 0;
    this._stopCount = 0;
    this._jumpCount = 0;
    this._jumpPeak = 0;
    this._movementSuccess = true;
};

/* 是否该位置 */
Game_CharacterBase.prototype.pos = function(x, y) {
    return this._x === x &amp;&amp; this._y === y;
};

/* 是否该位置且不能穿透 */
Game_CharacterBase.prototype.posNt = function(x, y) {
    // No through
    return this.pos(x, y) &amp;&amp; !this.isThrough();
};

/* 移动速度 */
Game_CharacterBase.prototype.moveSpeed = function() {
    return this._moveSpeed;
};

/* 设置移动速度 */
Game_CharacterBase.prototype.setMoveSpeed = function(moveSpeed) {
    this._moveSpeed = moveSpeed;
};

/* 移动频率 */
Game_CharacterBase.prototype.moveFrequency = function() {
    return this._moveFrequency;
};

/* 设置移动频率 */
Game_CharacterBase.prototype.setMoveFrequency = function(moveFrequency) {
    this._moveFrequency = moveFrequency;
};

/* 不透明度 */
Game_CharacterBase.prototype.opacity = function() {
    return this._opacity;
};

/* 设置不透明度 */
Game_CharacterBase.prototype.setOpacity = function(opacity) {
    this._opacity = opacity;
};

/* 混合模式 */
Game_CharacterBase.prototype.blendMode = function() {
    return this._blendMode;
};

/* 设置混合模式 */
Game_CharacterBase.prototype.setBlendMode = function(blendMode) {
    this._blendMode = blendMode;
};

/* 是否正常的优先级 */
Game_CharacterBase.prototype.isNormalPriority = function() {
    return this._priorityType === 1;
};

/* 设置优先级类型  */
Game_CharacterBase.prototype.setPriorityType = function(priorityType) {
    this._priorityType = priorityType;
};

/* 是否移动 */
Game_CharacterBase.prototype.isMoving = function() {
    return this._realX !== this._x || this._realY !== this._y;
};

/* 是否跳跃 */
Game_CharacterBase.prototype.isJumping = function() {
    return this._jumpCount &gt; 0;
};

/* 跳跃高度 */
Game_CharacterBase.prototype.jumpHeight = function() {
    return (this._jumpPeak * this._jumpPeak -
            Math.pow(Math.abs(this._jumpCount - this._jumpPeak), 2)) / 2;
};

/* 是否停止中 */
Game_CharacterBase.prototype.isStopping = function() {
    return !this.isMoving() &amp;&amp; !this.isJumping();
};

/* 检测停止 */
Game_CharacterBase.prototype.checkStop = function(threshold) {
    return this._stopCount &gt; threshold;
};

/* 重置停止计数 */
Game_CharacterBase.prototype.resetStopCount = function() {
    this._stopCount = 0;
};

/* 实际移动速度 */
Game_CharacterBase.prototype.realMoveSpeed = function() {
    return this._moveSpeed + (this.isDashing() ? 1 : 0);
};

/* 每帧距离 */
Game_CharacterBase.prototype.distancePerFrame = function() {
    return Math.pow(2, this.realMoveSpeed()) / 256;
};

/* 是否奔跑 */
Game_CharacterBase.prototype.isDashing = function() {
    return false;
};

/* 是否调试穿透 */
Game_CharacterBase.prototype.isDebugThrough = function() {
    return false;
};

/* 端正 */
Game_CharacterBase.prototype.straighten = function() {
    if (this.hasWalkAnime() || this.hasStepAnime()) {
        this._pattern = 1;
    }
    this._animationCount = 0;
};

/* 翻转方向 
 * @param {Number} d 方向（2：下，4：左，6：右，8：上） 
 */
Game_CharacterBase.prototype.reverseDir = function(d) {
    return 10 - d;
};

/* 是否可通行 */
Game_CharacterBase.prototype.canPass = function(x, y, d) {
    var x2 = $gameMap.roundXWithDirection(x, d);
    var y2 = $gameMap.roundYWithDirection(y, d);
    if (!$gameMap.isValid(x2, y2)) {
        return false;
    }
    if (this.isThrough() || this.isDebugThrough()) {
        return true;
    }
    if (!this.isMapPassable(x, y, d)) {
        return false;
    }
    if (this.isCollidedWithCharacters(x2, y2)) {
        return false;
    }
    return true;
};

/* 斜向是否可通行 */
Game_CharacterBase.prototype.canPassDiagonally = function(x, y, horz, vert) {
    var x2 = $gameMap.roundXWithDirection(x, horz);
    var y2 = $gameMap.roundYWithDirection(y, vert);
    if (this.canPass(x, y, vert) &amp;&amp; this.canPass(x, y2, horz)) {
        return true;
    }
    if (this.canPass(x, y, horz) &amp;&amp; this.canPass(x2, y, vert)) {
        return true;
    }
    return false;
};

/* 地图是否可通行 */
Game_CharacterBase.prototype.isMapPassable = function(x, y, d) {
    var x2 = $gameMap.roundXWithDirection(x, d);
    var y2 = $gameMap.roundYWithDirection(y, d);
    var d2 = this.reverseDir(d);
    return $gameMap.isPassable(x, y, d) &amp;&amp; $gameMap.isPassable(x2, y2, d2);
};

/* 是否和人物（事件和载具）碰撞 */
Game_CharacterBase.prototype.isCollidedWithCharacters = function(x, y) {
    return this.isCollidedWithEvents(x, y) || this.isCollidedWithVehicles(x, y);
};

/* 是否和事件碰撞 */
Game_CharacterBase.prototype.isCollidedWithEvents = function(x, y) {
    var events = $gameMap.eventsXyNt(x, y);
    return events.some(function(event) {
        return event.isNormalPriority();
    });
};

/* 是否和载具碰撞 */
Game_CharacterBase.prototype.isCollidedWithVehicles = function(x, y) {
    return $gameMap.boat().posNt(x, y) || $gameMap.ship().posNt(x, y);
};

/* 设置位置 */
Game_CharacterBase.prototype.setPosition = function(x, y) {
    this._x = Math.round(x);
    this._y = Math.round(y);
    this._realX = x;
    this._realY = y;
};

/* 复制位置 */
Game_CharacterBase.prototype.copyPosition = function(character) {
    this._x = character._x;
    this._y = character._y;
    this._realX = character._realX;
    this._realY = character._realY;
    this._direction = character._direction;
};

/* 放置 */
Game_CharacterBase.prototype.locate = function(x, y) {
    this.setPosition(x, y);
    this.straighten();
    this.refreshBushDepth();
};

/* 距离 */
Game_CharacterBase.prototype.direction = function() {
    return this._direction;
};

/* 设置距离 */
Game_CharacterBase.prototype.setDirection = function(d) {
    if (!this.isDirectionFixed() &amp;&amp; d) {
        this._direction = d;
    }
    this.resetStopCount();
};

/* 是否图块 */
Game_CharacterBase.prototype.isTile = function() {
    return this._tileId &gt; 0 &amp;&amp; this._priorityType === 0;
};

/* 是否物体的行走图 */
Game_CharacterBase.prototype.isObjectCharacter = function() {
    return this._isObjectCharacter;
};

/* Y 轴偏移像素 */
Game_CharacterBase.prototype.shiftY = function() {
    return this.isObjectCharacter() ? 0 : 6;
};

/* 滚动 X 坐标 */
Game_CharacterBase.prototype.scrolledX = function() {
    return $gameMap.adjustX(this._realX);
};

/* 滚动 Y 坐标 */
Game_CharacterBase.prototype.scrolledY = function() {
    return $gameMap.adjustY(this._realY);
};

/* 画面 X 坐标 */
Game_CharacterBase.prototype.screenX = function() {
    var tw = $gameMap.tileWidth();
    return Math.round(this.scrolledX() * tw + tw / 2);
};

/* 画面 Y 坐标 */
Game_CharacterBase.prototype.screenY = function() {
    var th = $gameMap.tileHeight();
    return Math.round(this.scrolledY() * th + th -
                      this.shiftY() - this.jumpHeight());
};

/* 画面 Z 坐标 */
Game_CharacterBase.prototype.screenZ = function() {
    return this._priorityType * 2 + 1;
}; 

/* 是否在画面附近 */
Game_CharacterBase.prototype.isNearTheScreen = function() {
    var gw = Graphics.width;
    var gh = Graphics.height;
    var tw = $gameMap.tileWidth();
    var th = $gameMap.tileHeight();
    var px = this.scrolledX() * tw + tw / 2 - gw / 2;
    var py = this.scrolledY() * th + th / 2 - gh / 2;
    return px &gt;= -gw &amp;&amp; px &lt;= gw &amp;&amp; py &gt;= -gh &amp;&amp; py &lt;= gh;
};

/* 更新 */
Game_CharacterBase.prototype.update = function() {
    if (this.isStopping()) {
        this.updateStop();
    }
    if (this.isJumping()) {
        this.updateJump();
    } else if (this.isMoving()) {
        this.updateMove();
    }
    this.updateAnimation();
};

/* 更新停止 */
Game_CharacterBase.prototype.updateStop = function() {
    this._stopCount;
};

/* 更新跳跃 */
Game_CharacterBase.prototype.updateJump = function() {
    this._jumpCount--;
    this._realX = (this._realX * this._jumpCount + this._x) / (this._jumpCount + 1.0);
    this._realY = (this._realY * this._jumpCount + this._y) / (this._jumpCount + 1.0);
    this.refreshBushDepth();
    if (this._jumpCount === 0) {
        this._realX = this._x = $gameMap.roundX(this._x);
        this._realY = this._y = $gameMap.roundY(this._y);
    }
};

/* 更新移动 */
Game_CharacterBase.prototype.updateMove = function() {
    if (this._x &lt; this._realX) {
        this._realX = Math.max(this._realX - this.distancePerFrame(), this._x);
    }
    if (this._x &gt; this._realX) {
        this._realX = Math.min(this._realX + this.distancePerFrame(), this._x);
    }
    if (this._y &lt; this._realY) {
        this._realY = Math.max(this._realY - this.distancePerFrame(), this._y);
    }
    if (this._y &gt; this._realY) {
        this._realY = Math.min(this._realY + this.distancePerFrame(), this._y);
    }
    if (!this.isMoving()) {
        this.refreshBushDepth();
    }
};

/* 更新动画 */
Game_CharacterBase.prototype.updateAnimation = function() {
    this.updateAnimationCount();
    if (this._animationCount &gt;= this.animationWait()) {
        this.updatePattern();
        this._animationCount = 0;
    }
};

/* 动画等待 */
Game_CharacterBase.prototype.animationWait = function() {
    return (9 - this.realMoveSpeed()) * 3;
};

/* 更新动画计数 */
Game_CharacterBase.prototype.updateAnimationCount = function() {
    if (this.isMoving() &amp;&amp; this.hasWalkAnime()) {
        this._animationCount += 1.5;
    } else if (this.hasStepAnime() || !this.isOriginalPattern()) {
        this._animationCount;
    }
};

/* 更新图案 */
Game_CharacterBase.prototype.updatePattern = function() {
    if (!this.hasStepAnime() &amp;&amp; this._stopCount &gt; 0) {
        this.resetPattern();
    } else {
        this._pattern = (this._pattern + 1) % this.maxPattern();
    }
};

/* 最大图案数
 * 行走图一个动画的最大图案数，也可以说是帧数。
 */
Game_CharacterBase.prototype.maxPattern = function() {
    return 4;
};

/* 图案
 * 当前行走图动画显示第几帧图案。一个动画 4 帧，资源图片只有 3 帧，第 4 帧与第 2 帧一样（ 第 1 帧 _pattern 为 0）。
 */
Game_CharacterBase.prototype.pattern = function() {
    return this._pattern &lt; 3 ? this._pattern : 1;
};

/* 设置图案 */
Game_CharacterBase.prototype.setPattern = function(pattern) {
    this._pattern = pattern;
};

/* 是否起始图案 */
Game_CharacterBase.prototype.isOriginalPattern = function() {
    return this.pattern() === 1;
};

/* 重置图案 */
Game_CharacterBase.prototype.resetPattern = function() {
    this.setPattern(1);
};

/* 刷新草木繁茂处深度 */
Game_CharacterBase.prototype.refreshBushDepth = function() {
    if (this.isNormalPriority() &amp;&amp; !this.isObjectCharacter() &amp;&amp;
            this.isOnBush() &amp;&amp; !this.isJumping()) {
        if (!this.isMoving()) {
            this._bushDepth = 12;
        }
    } else {
        this._bushDepth = 0;
    }
};

/* 是否在梯子上 */
Game_CharacterBase.prototype.isOnLadder = function() {
    return $gameMap.isLadder(this._x, this._y);
};

/* 是否在草木繁茂处上 */
Game_CharacterBase.prototype.isOnBush = function() {
    return $gameMap.isBush(this._x, this._y);
};

/* 地形标志 */
Game_CharacterBase.prototype.terrainTag = function() {
    return $gameMap.terrainTag(this._x, this._y);
};

/* 区域 ID */
Game_CharacterBase.prototype.regionId = function() {
    return $gameMap.regionId(this._x, this._y);
};

/* 增加步数 */
Game_CharacterBase.prototype.increaseSteps = function() {
    if (this.isOnLadder()) {
        this.setDirection(8);
    }
    this.resetStopCount();
    this.refreshBushDepth();
};

/* 图块 ID */
Game_CharacterBase.prototype.tileId = function() {
    return this._tileId;
};

/* 行走图名称 */
Game_CharacterBase.prototype.characterName = function() {
    return this._characterName;
};

/* 行走图索引 */
Game_CharacterBase.prototype.characterIndex = function() {
    return this._characterIndex;
};

/* 设置图像 */
Game_CharacterBase.prototype.setImage = function(characterName, characterIndex) {
    this._tileId = 0;
    this._characterName = characterName;
    this._characterIndex = characterIndex;
    this._isObjectCharacter = ImageManager.isObjectCharacter(characterName);
};

/* 设置图块图像 */
Game_CharacterBase.prototype.setTileImage = function(tileId) {
    this._tileId = tileId;
    this._characterName = '';
    this._characterIndex = 0;
    this._isObjectCharacter = true;
};

/* 检测前方的接触的事件触发条件 */
Game_CharacterBase.prototype.checkEventTriggerTouchFront = function(d) {
    var x2 = $gameMap.roundXWithDirection(this._x, d);
    var y2 = $gameMap.roundYWithDirection(this._y, d);
    this.checkEventTriggerTouch(x2, y2);
};

/* 检测接触的事件触发条件*/
Game_CharacterBase.prototype.checkEventTriggerTouch = function(x, y) {
    return false;
};

/* 是否移动成功 */
Game_CharacterBase.prototype.isMovementSucceeded = function(x, y) {
    return this._movementSuccess;
};

/* 设置移动成功*/
Game_CharacterBase.prototype.setMovementSuccess = function(success) {
    this._movementSuccess = success;
};

/* 直线移动 */
Game_CharacterBase.prototype.moveStraight = function(d) {
    this.setMovementSuccess(this.canPass(this._x, this._y, d));
    if (this.isMovementSucceeded()) {
        this.setDirection(d);
        this._x = $gameMap.roundXWithDirection(this._x, d);
        this._y = $gameMap.roundYWithDirection(this._y, d);
        this._realX = $gameMap.xWithDirection(this._x, this.reverseDir(d));
        this._realY = $gameMap.yWithDirection(this._y, this.reverseDir(d));
        this.increaseSteps();
    } else {
        this.setDirection(d);
        this.checkEventTriggerTouchFront(d);
    }
};

/* 斜线移动 */
Game_CharacterBase.prototype.moveDiagonally = function(horz, vert) {
    this.setMovementSuccess(this.canPassDiagonally(this._x, this._y, horz, vert));
    if (this.isMovementSucceeded()) {
        this._x = $gameMap.roundXWithDirection(this._x, horz);
        this._y = $gameMap.roundYWithDirection(this._y, vert);
        this._realX = $gameMap.xWithDirection(this._x, this.reverseDir(horz));
        this._realY = $gameMap.yWithDirection(this._y, this.reverseDir(vert));
        this.increaseSteps();
    }
    if (this._direction === this.reverseDir(horz)) {
        this.setDirection(horz);
    }
    if (this._direction === this.reverseDir(vert)) {
        this.setDirection(vert);
    }
};

/* 跳跃 */
Game_CharacterBase.prototype.jump = function(xPlus, yPlus) {
    if (Math.abs(xPlus) &gt; Math.abs(yPlus)) {
        if (xPlus !== 0) {
            this.setDirection(xPlus &lt; 0 ? 4 : 6);
        }
    } else {
        if (yPlus !== 0) {
            this.setDirection(yPlus &lt; 0 ? 8 : 2);
        }
    }
    this._x += xPlus;
    this._y += yPlus;
    var distance = Math.round(Math.sqrt(xPlus * xPlus + yPlus * yPlus));
    this._jumpPeak = 10 + distance - this._moveSpeed;
    this._jumpCount = this._jumpPeak * 2;
    this.resetStopCount();
    this.straighten();
};

/* 是否有行走动画 */
Game_CharacterBase.prototype.hasWalkAnime = function() {
    return this._walkAnime;
};

/* 设置行走动画 */
Game_CharacterBase.prototype.setWalkAnime = function(walkAnime) {
    this._walkAnime = walkAnime;
};

/* 是否有踏步动画 */
Game_CharacterBase.prototype.hasStepAnime = function() {
    return this._stepAnime;
};

/* 设置踏步动画 */
Game_CharacterBase.prototype.setStepAnime = function(stepAnime) {
    this._stepAnime = stepAnime;
};

/* 是否方向固定 */
Game_CharacterBase.prototype.isDirectionFixed = function() {
    return this._directionFix;
};

/* 设置方向固定 */
Game_CharacterBase.prototype.setDirectionFix = function(directionFix) {
    this._directionFix = directionFix;
};

/* 是否穿透 */
Game_CharacterBase.prototype.isThrough = function() {
    return this._through;
};

/* 设置穿透 */
Game_CharacterBase.prototype.setThrough = function(through) {
    this._through = through;
};

/* 是否透明 */
Game_CharacterBase.prototype.isTransparent = function() {
    return this._transparent;
};

/* 草木繁茂处深度 */
Game_CharacterBase.prototype.bushDepth = function() {
    return this._bushDepth;
};

/* 设置透明 */
Game_CharacterBase.prototype.setTransparent = function(transparent) {
    this._transparent = transparent;
};

/* 请求动画 */
Game_CharacterBase.prototype.requestAnimation = function(animationId) {
    this._animationId = animationId;
};

/* 请求气泡图标 */
Game_CharacterBase.prototype.requestBalloon = function(balloonId) {
    this._balloonId = balloonId;
};

/* 动画 ID */
Game_CharacterBase.prototype.animationId = function() {
    return this._animationId;
};

/* 气泡图标 ID */
Game_CharacterBase.prototype.balloonId = function() {
    return this._balloonId;
};

/* 开始动画 */
Game_CharacterBase.prototype.startAnimation = function() {
    this._animationId = 0;
    this._animationPlaying = true;
};

/* 开始气泡图标 */
Game_CharacterBase.prototype.startBalloon = function() {
    this._balloonId = 0;
    this._balloonPlaying = true;
};

/* 是否动画播放中 */
Game_CharacterBase.prototype.isAnimationPlaying = function() {
    return this._animationId &gt; 0 || this._animationPlaying;
};

/* 是否气泡图标播放中 */
Game_CharacterBase.prototype.isBalloonPlaying = function() {
    return this._balloonId &gt; 0 || this._balloonPlaying;
};

/* 结束动画 */
Game_CharacterBase.prototype.endAnimation = function() {
    this._animationPlaying = false;
};

/* 结束气泡图标 */
Game_CharacterBase.prototype.endBalloon = function() {
    this._balloonPlaying = false;
};

//-----------------------------------------------------------------------------
// 游戏_人物
// Game_Character
// 
// Game_Player、Game_Follower、GameVehicle 和 Game_Event 的父类。
// The superclass of Game_Player, Game_Follower, GameVehicle, and Game_Event.

function Game_Character() {
    this.initialize.apply(this, arguments);
}

Game_Character.prototype = Object.create(Game_CharacterBase.prototype);
Game_Character.prototype.constructor = Game_Character;

Game_Character.ROUTE_END               = 0;   // 移动路线-结束 
Game_Character.ROUTE_MOVE_DOWN         = 1;   // 移动路线-向下移动 
Game_Character.ROUTE_MOVE_LEFT         = 2;   // 移动路线-向左移动 
Game_Character.ROUTE_MOVE_RIGHT        = 3;   // 移动路线-向右移动 
Game_Character.ROUTE_MOVE_UP           = 4;   // 移动路线-向上移动 
Game_Character.ROUTE_MOVE_LOWER_L      = 5;   // 移动路线-向左下移动 
Game_Character.ROUTE_MOVE_LOWER_R      = 6;   // 移动路线-向右下移动 
Game_Character.ROUTE_MOVE_UPPER_L      = 7;   // 移动路线-向左上移动 
Game_Character.ROUTE_MOVE_UPPER_R      = 8;   // 移动路线-向右上移动 
Game_Character.ROUTE_MOVE_RANDOM       = 9;   // 移动路线-随机移动 
Game_Character.ROUTE_MOVE_TOWARD       = 10;  // 移动路线-接近玩家 
Game_Character.ROUTE_MOVE_AWAY         = 11;  // 移动路线-远离玩家 
Game_Character.ROUTE_MOVE_FORWARD      = 12;  // 移动路线-前进一步 
Game_Character.ROUTE_MOVE_BACKWARD     = 13;  // 移动路线-后退一步 
Game_Character.ROUTE_JUMP              = 14;  // 移动路线-跳跃 
Game_Character.ROUTE_WAIT              = 15;  // 移动路线-等待 
Game_Character.ROUTE_TURN_DOWN         = 16;  // 移动路线-朝向下方 
Game_Character.ROUTE_TURN_LEFT         = 17;  // 移动路线-朝向左方 
Game_Character.ROUTE_TURN_RIGHT        = 18;  // 移动路线-朝向右方 
Game_Character.ROUTE_TURN_UP           = 19;  // 移动路线-朝向上方 
Game_Character.ROUTE_TURN_90D_R        = 20;  // 移动路线-右转 90° 
Game_Character.ROUTE_TURN_90D_L        = 21;  // 移动路线-左转 90° 
Game_Character.ROUTE_TURN_180D         = 22;  // 移动路线-后转 180° 
Game_Character.ROUTE_TURN_90D_R_L      = 23;  // 移动路线-向左或向右转 90° 
Game_Character.ROUTE_TURN_RANDOM       = 24;  // 移动路线-随机转向 
Game_Character.ROUTE_TURN_TOWARD       = 25;  // 移动路线-朝向玩家 
Game_Character.ROUTE_TURN_AWAY         = 26;  // 移动路线-背向玩家 
Game_Character.ROUTE_SWITCH_ON         = 27;  // 移动路线-打开开关 
Game_Character.ROUTE_SWITCH_OFF        = 28;  // 移动路线-关闭开关 
Game_Character.ROUTE_CHANGE_SPEED      = 29;  // 移动路线-更改移动速度 
Game_Character.ROUTE_CHANGE_FREQ       = 30;  // 移动路线-更改移动频率 
Game_Character.ROUTE_WALK_ANIME_ON     = 31;  // 移动路线-开启步行动画 
Game_Character.ROUTE_WALK_ANIME_OFF    = 32;  // 移动路线-关闭步行动画 
Game_Character.ROUTE_STEP_ANIME_ON     = 33;  // 移动路线-开启踏步动画 
Game_Character.ROUTE_STEP_ANIME_OFF    = 34;  // 移动路线-关闭踏步动画 
Game_Character.ROUTE_DIR_FIX_ON        = 35;  // 移动路线-开启固定朝向 
Game_Character.ROUTE_DIR_FIX_OFF       = 36;  // 移动路线-关闭固定朝向 
Game_Character.ROUTE_THROUGH_ON        = 37;  // 移动路线-开启穿透 
Game_Character.ROUTE_THROUGH_OFF       = 38;  // 移动路线-关闭穿透 
Game_Character.ROUTE_TRANSPARENT_ON    = 39;  // 移动路线-开启透明状态 
Game_Character.ROUTE_TRANSPARENT_OFF   = 40;  // 移动路线-关闭透明状态 
Game_Character.ROUTE_CHANGE_IMAGE      = 41;  // 移动路线-更改图像 
Game_Character.ROUTE_CHANGE_OPACITY    = 42;  // 移动路线-更改不透明度 
Game_Character.ROUTE_CHANGE_BLEND_MODE = 43;  // 移动路线-更改合成方式 
Game_Character.ROUTE_PLAY_SE           = 44;  // 移动路线-播放 SE 
Game_Character.ROUTE_SCRIPT            = 45;  // 移动路线-脚本 

/* 初始化 */
Game_Character.prototype.initialize = function() {
    Game_CharacterBase.prototype.initialize.call(this);
};

/* 初始化成员 */
Game_Character.prototype.initMembers = function() {
    Game_CharacterBase.prototype.initMembers.call(this);
    this._moveRouteForcing = false;
    this._moveRoute = null;
    this._moveRouteIndex = 0;
    this._originalMoveRoute = null;
    this._originalMoveRouteIndex = 0;
    this._waitCount = 0;
};

/* 记录移动路线 */
Game_Character.prototype.memorizeMoveRoute = function() {
    this._originalMoveRoute       = this._moveRoute;
    this._originalMoveRouteIndex  = this._moveRouteIndex;
};

/* 恢复移动路线 */
Game_Character.prototype.restoreMoveRoute = function() {
    this._moveRoute          = this._originalMoveRoute;
    this._moveRouteIndex     = this._originalMoveRouteIndex;
    this._originalMoveRoute  = null;
};

/* 是否强制移动 */
Game_Character.prototype.isMoveRouteForcing = function() {
    return this._moveRouteForcing;
};

/* 设置移动路线 */
Game_Character.prototype.setMoveRoute = function(moveRoute) {
    this._moveRoute = moveRoute;
    this._moveRouteIndex = 0;
    this._moveRouteForcing = false;
};

/* 强制移动路线 */
Game_Character.prototype.forceMoveRoute = function(moveRoute) {
    if (!this._originalMoveRoute) {
        this.memorizeMoveRoute();
    }
    this._moveRoute = moveRoute;
    this._moveRouteIndex = 0;
    this._moveRouteForcing = true;
    this._waitCount = 0;
};

/* 更新停止 */
Game_Character.prototype.updateStop = function() {
    Game_CharacterBase.prototype.updateStop.call(this);
    if (this._moveRouteForcing) {
        this.updateRoutineMove();
    }
};

/* 更新一系列移动 */
Game_Character.prototype.updateRoutineMove = function() {
    if (this._waitCount &gt; 0) {
        this._waitCount--;
    } else {
        this.setMovementSuccess(true);
        var command = this._moveRoute.list[this._moveRouteIndex];
        if (command) {
            this.processMoveCommand(command);
            this.advanceMoveRouteIndex();
        }
    }
};

/* 处理移动指令 */
Game_Character.prototype.processMoveCommand = function(command) {
    var gc = Game_Character;
    var params = command.parameters;
    switch (command.code) {
    case gc.ROUTE_END:
        this.processRouteEnd();
        break;
    case gc.ROUTE_MOVE_DOWN:
        this.moveStraight(2);
        break;
    case gc.ROUTE_MOVE_LEFT:
        this.moveStraight(4);
        break;
    case gc.ROUTE_MOVE_RIGHT:
        this.moveStraight(6);
        break;
    case gc.ROUTE_MOVE_UP:
        this.moveStraight(8);
        break;
    case gc.ROUTE_MOVE_LOWER_L:
        this.moveDiagonally(4, 2);
        break;
    case gc.ROUTE_MOVE_LOWER_R:
        this.moveDiagonally(6, 2);
        break;
    case gc.ROUTE_MOVE_UPPER_L:
        this.moveDiagonally(4, 8);
        break;
    case gc.ROUTE_MOVE_UPPER_R:
        this.moveDiagonally(6, 8);
        break;
    case gc.ROUTE_MOVE_RANDOM:
        this.moveRandom();
        break;
    case gc.ROUTE_MOVE_TOWARD:
        this.moveTowardPlayer();
        break;
    case gc.ROUTE_MOVE_AWAY:
        this.moveAwayFromPlayer();
        break;
    case gc.ROUTE_MOVE_FORWARD:
        this.moveForward();
        break;
    case gc.ROUTE_MOVE_BACKWARD:
        this.moveBackward();
        break;
    case gc.ROUTE_JUMP:
        this.jump(params[0], params[1]);
        break;
    case gc.ROUTE_WAIT:
        this._waitCount = params[0] - 1;
        break;
    case gc.ROUTE_TURN_DOWN:
        this.setDirection(2);
        break;
    case gc.ROUTE_TURN_LEFT:
        this.setDirection(4);
        break;
    case gc.ROUTE_TURN_RIGHT:
        this.setDirection(6);
        break;
    case gc.ROUTE_TURN_UP:
        this.setDirection(8);
        break;
    case gc.ROUTE_TURN_90D_R:
        this.turnRight90();
        break;
    case gc.ROUTE_TURN_90D_L:
        this.turnLeft90();
        break;
    case gc.ROUTE_TURN_180D:
        this.turn180();
        break;
    case gc.ROUTE_TURN_90D_R_L:
        this.turnRightOrLeft90();
        break;
    case gc.ROUTE_TURN_RANDOM:
        this.turnRandom();
        break;
    case gc.ROUTE_TURN_TOWARD:
        this.turnTowardPlayer();
        break;
    case gc.ROUTE_TURN_AWAY:
        this.turnAwayFromPlayer();
        break;
    case gc.ROUTE_SWITCH_ON:
        $gameSwitches.setValue(params[0], true);
        break;
    case gc.ROUTE_SWITCH_OFF:
        $gameSwitches.setValue(params[0], false);
        break;
    case gc.ROUTE_CHANGE_SPEED:
        this.setMoveSpeed(params[0]);
        break;
    case gc.ROUTE_CHANGE_FREQ:
        this.setMoveFrequency(params[0]);
        break;
    case gc.ROUTE_WALK_ANIME_ON:
        this.setWalkAnime(true);
        break;
    case gc.ROUTE_WALK_ANIME_OFF:
        this.setWalkAnime(false);
        break;
    case gc.ROUTE_STEP_ANIME_ON:
        this.setStepAnime(true);
        break;
    case gc.ROUTE_STEP_ANIME_OFF:
        this.setStepAnime(false);
        break;
    case gc.ROUTE_DIR_FIX_ON:
        this.setDirectionFix(true);
        break;
    case gc.ROUTE_DIR_FIX_OFF:
        this.setDirectionFix(false);
        break;
    case gc.ROUTE_THROUGH_ON:
        this.setThrough(true);
        break;
    case gc.ROUTE_THROUGH_OFF:
        this.setThrough(false);
        break;
    case gc.ROUTE_TRANSPARENT_ON:
        this.setTransparent(true);
        break;
    case gc.ROUTE_TRANSPARENT_OFF:
        this.setTransparent(false);
        break;
    case gc.ROUTE_CHANGE_IMAGE:
        this.setImage(params[0], params[1]);
        break;
    case gc.ROUTE_CHANGE_OPACITY:
        this.setOpacity(params[0]);
        break;
    case gc.ROUTE_CHANGE_BLEND_MODE:
        this.setBlendMode(params[0]);
        break;
    case gc.ROUTE_PLAY_SE:
        AudioManager.playSe(params[0]);
        break;
    case gc.ROUTE_SCRIPT:
        eval(params[0]);
        break;
    }
};

/* 与该 X 位置差值 */
Game_Character.prototype.deltaXFrom = function(x) {
    return $gameMap.deltaX(this.x, x);
};

/* 与该 Y 位置差值 */
Game_Character.prototype.deltaYFrom = function(y) {
    return $gameMap.deltaY(this.y, y);
};

/* 随机移动 */
Game_Character.prototype.moveRandom = function() {
    var d = 2 + Math.randomInt(4) * 2;
    if (this.canPass(this.x, this.y, d)) {
        this.moveStraight(d);
    }
};

/* 接近该人物移动 */
Game_Character.prototype.moveTowardCharacter = function(character) {
    var sx = this.deltaXFrom(character.x);
    var sy = this.deltaYFrom(character.y);
    if (Math.abs(sx) &gt; Math.abs(sy)) {
        this.moveStraight(sx &gt; 0 ? 4 : 6);
        if (!this.isMovementSucceeded() &amp;&amp; sy !== 0) {
            this.moveStraight(sy &gt; 0 ? 8 : 2);
        }
    } else if (sy !== 0) {
        this.moveStraight(sy &gt; 0 ? 8 : 2);
        if (!this.isMovementSucceeded() &amp;&amp; sx !== 0) {
            this.moveStraight(sx &gt; 0 ? 4 : 6);
        }
    }
};

/* 远离该人物移动 */
Game_Character.prototype.moveAwayFromCharacter = function(character) {
    var sx = this.deltaXFrom(character.x);
    var sy = this.deltaYFrom(character.y);
    if (Math.abs(sx) &gt; Math.abs(sy)) {
        this.moveStraight(sx &gt; 0 ? 6 : 4);
        if (!this.isMovementSucceeded() &amp;&amp; sy !== 0) {
            this.moveStraight(sy &gt; 0 ? 2 : 8);
        }
    } else if (sy !== 0) {
        this.moveStraight(sy &gt; 0 ? 2 : 8);
        if (!this.isMovementSucceeded() &amp;&amp; sx !== 0) {
            this.moveStraight(sx &gt; 0 ? 6 : 4);
        }
    }
};

/* 朝向该人物 */
Game_Character.prototype.turnTowardCharacter = function(character) {
    var sx = this.deltaXFrom(character.x);
    var sy = this.deltaYFrom(character.y);
    if (Math.abs(sx) &gt; Math.abs(sy)) {
        this.setDirection(sx &gt; 0 ? 4 : 6);
    } else if (sy !== 0) {
        this.setDirection(sy &gt; 0 ? 8 : 2);
    }
};

/* 背向该人物 */
Game_Character.prototype.turnAwayFromCharacter = function(character) {
    var sx = this.deltaXFrom(character.x);
    var sy = this.deltaYFrom(character.y);
    if (Math.abs(sx) &gt; Math.abs(sy)) {
        this.setDirection(sx &gt; 0 ? 6 : 4);
    } else if (sy !== 0) {
        this.setDirection(sy &gt; 0 ? 2 : 8);
    }
};

/* 朝向玩家 */
Game_Character.prototype.turnTowardPlayer = function() {
    this.turnTowardCharacter($gamePlayer);
};

/* 背向玩家 */
Game_Character.prototype.turnAwayFromPlayer = function() {
    this.turnAwayFromCharacter($gamePlayer);
};

/* 接近玩家 */
Game_Character.prototype.moveTowardPlayer = function() {
    this.moveTowardCharacter($gamePlayer);
};

/* 远离玩家 */
Game_Character.prototype.moveAwayFromPlayer = function() {
    this.moveAwayFromCharacter($gamePlayer);
};

/* 前进一步 */
Game_Character.prototype.moveForward = function() {
    this.moveStraight(this.direction());
};

/* 后退一步 */
Game_Character.prototype.moveBackward = function() {
    var lastDirectionFix = this.isDirectionFixed();
    this.setDirectionFix(true);
    this.moveStraight(this.reverseDir(this.direction()));
    this.setDirectionFix(lastDirectionFix);
};

/* 处理路线结束 */
Game_Character.prototype.processRouteEnd = function() {
    if (this._moveRoute.repeat) {
        this._moveRouteIndex = -1;
    } else if (this._moveRouteForcing) {
        this._moveRouteForcing = false;
        this.restoreMoveRoute();
    }
};

/* 增加移动路线索引 */
Game_Character.prototype.advanceMoveRouteIndex = function() {
    var moveRoute = this._moveRoute;
    if (moveRoute &amp;&amp; (this.isMovementSucceeded() || moveRoute.skippable)) {
        var numCommands = moveRoute.list.length - 1;
        this._moveRouteIndex;
        if (moveRoute.repeat &amp;&amp; this._moveRouteIndex &gt;= numCommands) {
            this._moveRouteIndex = 0;
        }
    }
};

/* 右转 90° */
Game_Character.prototype.turnRight90 = function() {
    switch (this.direction()) {
    case 2:
        this.setDirection(4);
        break;
    case 4:
        this.setDirection(8);
        break;
    case 6:
        this.setDirection(2);
        break;
    case 8:
        this.setDirection(6);
        break;
    }
};

/* 左转 90° */
Game_Character.prototype.turnLeft90 = function() {
    switch (this.direction()) {
    case 2:
        this.setDirection(6);
        break;
    case 4:
        this.setDirection(2);
        break;
    case 6:
        this.setDirection(8);
        break;
    case 8:
        this.setDirection(4);
        break;
    }
};

/* 后转 180° */
Game_Character.prototype.turn180 = function() {
    this.setDirection(this.reverseDir(this.direction()));
};

/* 向左或向右转 90° */
Game_Character.prototype.turnRightOrLeft90 = function() {
    switch (Math.randomInt(2)) {
    case 0:
        this.turnRight90();
        break;
    case 1:
        this.turnLeft90();
        break;
    }
};

/* 随机转向 */
Game_Character.prototype.turnRandom = function() {
    this.setDirection(2 + Math.randomInt(4) * 2);
};

/* 交换
 * 交换两个人的位置。
 */
Game_Character.prototype.swap = function(character) {
    var newX = character.x;
    var newY = character.y;
    character.locate(this.x, this.y);
    this.locate(newX, newY);
};

/* 寻找朝着该位置的方向 
 * 该寻路是 A* 算法的魔改，每走一步查找 12 步内的路径，取出第一步进行行走。 
 */
Game_Character.prototype.findDirectionTo = function(goalX, goalY) {
    var searchLimit = this.searchLimit();
    var mapWidth = $gameMap.width();
    var nodeList = [];
    var openList = [];
    var closedList = [];
    var start = {};
    var best = start;

    if (this.x === goalX &amp;&amp; this.y === goalY) {
        return 0;
    }

    start.parent = null;
    start.x = this.x;
    start.y = this.y;
    start.g = 0;
    start.f = $gameMap.distance(start.x, start.y, goalX, goalY);
    nodeList.push(start);
    openList.push(start.y * mapWidth + start.x);

    while (nodeList.length &gt; 0) {
        var bestIndex = 0;
        for (var i = 0; i &lt; nodeList.length; i) {
            if (nodeList[i].f &lt; nodeList[bestIndex].f) {
                bestIndex = i;
            }
        }

        var current = nodeList[bestIndex];
        var x1 = current.x;
        var y1 = current.y;
        var pos1 = y1 * mapWidth + x1;
        var g1 = current.g;

        nodeList.splice(bestIndex, 1);
        openList.splice(openList.indexOf(pos1), 1);
        closedList.push(pos1);

        if (current.x === goalX &amp;&amp; current.y === goalY) {
            best = current;
            break;
        }

        if (g1 &gt;= searchLimit) {
            continue;
        }

        for (var j = 0; j &lt; 4; j) {
            var direction = 2 + j * 2;
            var x2 = $gameMap.roundXWithDirection(x1, direction);
            var y2 = $gameMap.roundYWithDirection(y1, direction);
            var pos2 = y2 * mapWidth + x2;

            if (closedList.contains(pos2)) {
                continue;
            }
            if (!this.canPass(x1, y1, direction)) {
                continue;
            }

            var g2 = g1 + 1;
            var index2 = openList.indexOf(pos2);

            if (index2 &lt; 0 || g2 &lt; nodeList[index2].g) {
                var neighbor;
                if (index2 &gt;= 0) {
                    neighbor = nodeList[index2];
                } else {
                    neighbor = {};
                    nodeList.push(neighbor);
                    openList.push(pos2);
                }
                neighbor.parent = current;
                neighbor.x = x2;
                neighbor.y = y2;
                neighbor.g = g2;
                neighbor.f = g2 + $gameMap.distance(x2, y2, goalX, goalY);
                if (!best || neighbor.f - neighbor.g &lt; best.f - best.g) {
                    best = neighbor;
                }
            }
        }
    }

    var node = best;
    while (node.parent &amp;&amp; node.parent !== start) {
        node = node.parent;
    }

    var deltaX1 = $gameMap.deltaX(node.x, start.x);
    var deltaY1 = $gameMap.deltaY(node.y, start.y);
    if (deltaY1 &gt; 0) {
        return 2;
    } else if (deltaX1 &lt; 0) {
        return 4;
    } else if (deltaX1 &gt; 0) {
        return 6;
    } else if (deltaY1 &lt; 0) {
        return 8;
    }

    var deltaX2 = this.deltaXFrom(goalX);
    var deltaY2 = this.deltaYFrom(goalY);
    if (Math.abs(deltaX2) &gt; Math.abs(deltaY2)) {
        return deltaX2 &gt; 0 ? 4 : 6;
    } else if (deltaY2 !== 0) {
        return deltaY2 &gt; 0 ? 8 : 2;
    }

    return 0;
};

/* 查找上限 */
Game_Character.prototype.searchLimit = function() {
    return 12;
};

//-----------------------------------------------------------------------------
// 游戏_玩家 
// Game_Player
//
// 玩家的游戏对象类。它包含事件开始判定和地图滚动功能。
// The game object class for the player. It contains event starting
// determinants and map scrolling functions.

function Game_Player() {
    this.initialize.apply(this, arguments);
}

Game_Player.prototype = Object.create(Game_Character.prototype);
Game_Player.prototype.constructor = Game_Player;

/* 初始化 */
Game_Player.prototype.initialize = function() {
    Game_Character.prototype.initialize.call(this);
    this.setTransparent($dataSystem.optTransparent);
};

/* 初始化成员 */
Game_Player.prototype.initMembers = function() {
    Game_Character.prototype.initMembers.call(this);
    this._vehicleType = 'walk';
    this._vehicleGettingOn = false;
    this._vehicleGettingOff = false;
    this._dashing = false;
    this._needsMapReload = false;
    this._transferring = false;
    this._newMapId = 0;
    this._newX = 0;
    this._newY = 0;
    this._newDirection = 0;
    this._fadeType = 0;
    this._followers = new Game_Followers();
    this._encounterCount = 0;
};

/* 清除场所移动信息 */
Game_Player.prototype.clearTransferInfo = function() {
    this._transferring = false;
    this._newMapId = 0;
    this._newX = 0;
    this._newY = 0;
    this._newDirection = 0;
};

/* 跟随者 */
Game_Player.prototype.followers = function() {
    return this._followers;
};

/* 刷新 */
Game_Player.prototype.refresh = function() {
    var actor = $gameParty.leader();
    var characterName = actor ? actor.characterName() : '';
    var characterIndex = actor ? actor.characterIndex() : 0;
    this.setImage(characterName, characterIndex);
    this._followers.refresh();
};

/* 是否停止中 */
Game_Player.prototype.isStopping = function() {
    if (this._vehicleGettingOn || this._vehicleGettingOff) {
        return false;
    }
    return Game_Character.prototype.isStopping.call(this);
};

/* 储存场所移动 */
Game_Player.prototype.reserveTransfer = function(mapId, x, y, d, fadeType) {
    this._transferring = true;
    this._newMapId = mapId;
    this._newX = x;
    this._newY = y;
    this._newDirection = d;
    this._fadeType = fadeType;
};

/* 请求地图重载 */
Game_Player.prototype.requestMapReload = function() {
    this._needsMapReload = true;
};

/* 是否场所移动中 */
Game_Player.prototype.isTransferring = function() {
    return this._transferring;
};

/* 新地图 ID */
Game_Player.prototype.newMapId = function() {
    return this._newMapId;
};

/* 渐变类型 */
Game_Player.prototype.fadeType = function() {
    return this._fadeType;
};

/* 表现场所移动 */
Game_Player.prototype.performTransfer = function() {
    if (this.isTransferring()) {
        this.setDirection(this._newDirection);
        if (this._newMapId !== $gameMap.mapId() || this._needsMapReload) {
            $gameMap.setup(this._newMapId);
            this._needsMapReload = false;
        }
        this.locate(this._newX, this._newY);
        this.refresh();
        this.clearTransferInfo();
    }
};

/* 是否地图可通行 */
Game_Player.prototype.isMapPassable = function(x, y, d) {
    var vehicle = this.vehicle();
    if (vehicle) {
        return vehicle.isMapPassable(x, y, d);
    } else {
        return Game_Character.prototype.isMapPassable.call(this, x, y, d);
    }
};

/* 载具 */
Game_Player.prototype.vehicle = function() {
    return $gameMap.vehicle(this._vehicleType);
};

/* 是否在小舟 */
Game_Player.prototype.isInBoat = function() {
    return this._vehicleType === 'boat';
};

/* 是否在大船 */
Game_Player.prototype.isInShip = function() {
    return this._vehicleType === 'ship';
};

/* 是否在飞艇 */
Game_Player.prototype.isInAirship = function() {
    return this._vehicleType === 'airship';
};

/* 是否在载具 */
Game_Player.prototype.isInVehicle = function() {
    return this.isInBoat() || this.isInShip() || this.isInAirship();
};

/* 是否普通 */
Game_Player.prototype.isNormal = function() {
    return this._vehicleType === 'walk' &amp;&amp; !this.isMoveRouteForcing();
};

/* 是否奔跑 */
Game_Player.prototype.isDashing = function() {
    return this._dashing;
};

/* 是否调试穿透 
 * 在调试模式下，按 ctrl 可使玩家穿透。
 */
Game_Player.prototype.isDebugThrough = function() {
    return Input.isPressed('control') &amp;&amp; $gameTemp.isPlaytest();
};

/* 是否碰撞 */
Game_Player.prototype.isCollided = function(x, y) {
    if (this.isThrough()) {
        return false;
    } else {
        return this.pos(x, y) || this._followers.isSomeoneCollided(x, y);
    }
};

/* 中心 X 位置*/
Game_Player.prototype.centerX = function() {
    return (Graphics.width / $gameMap.tileWidth() - 1) / 2.0;
};

/* 中心 Y 位置*/
Game_Player.prototype.centerY = function() {
    return (Graphics.height / $gameMap.tileHeight() - 1) / 2.0;
};

/* 中心位置 */
Game_Player.prototype.center = function(x, y) {
    return $gameMap.setDisplayPos(x - this.centerX(), y - this.centerY());
};

/* 放置 */
Game_Player.prototype.locate = function(x, y) {
    Game_Character.prototype.locate.call(this, x, y);
    this.center(x, y);
    this.makeEncounterCount();
    if (this.isInVehicle()) {
        this.vehicle().refresh();
    }
    this._followers.synchronize(x, y, this.direction());
};

/* 增加步数 */
Game_Player.prototype.increaseSteps = function() {
    Game_Character.prototype.increaseSteps.call(this);
    if (this.isNormal()) {
        $gameParty.increaseSteps();
    }
};

/* 制作遇敌计数 */
Game_Player.prototype.makeEncounterCount = function() {
    var n = $gameMap.encounterStep();
    this._encounterCount = Math.randomInt(n) + Math.randomInt(n) + 1;
};

/* 制作遇敌敌群 ID */
Game_Player.prototype.makeEncounterTroopId = function() {
    var encounterList = [];
    var weightSum = 0;
    $gameMap.encounterList().forEach(function(encounter) {
        if (this.meetsEncounterConditions(encounter)) {
            encounterList.push(encounter);
            weightSum += encounter.weight;
        }
    }, this);
    if (weightSum &gt; 0) {
        var value = Math.randomInt(weightSum);
        for (var i = 0; i &lt; encounterList.length; i) {
            value -= encounterList[i].weight;
            if (value &lt; 0) {
                return encounterList[i].troopId;
            }
        }
    }
    return 0;
};

/* 是否满足遇敌条件 */
Game_Player.prototype.meetsEncounterConditions = function(encounter) {
    return (encounter.regionSet.length === 0 ||
            encounter.regionSet.contains(this.regionId()));
};

/* 执行遇敌 */
Game_Player.prototype.executeEncounter = function() {
    if (!$gameMap.isEventRunning() &amp;&amp; this._encounterCount &lt;= 0) {
        this.makeEncounterCount();
        var troopId = this.makeEncounterTroopId();
        if ($dataTroops[troopId]) {
            BattleManager.setup(troopId, true, false);
            BattleManager.onEncounter();
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
};

/* 开始地图事件 */
Game_Player.prototype.startMapEvent = function(x, y, triggers, normal) {
    if (!$gameMap.isEventRunning()) {
        $gameMap.eventsXy(x, y).forEach(function(event) {
            if (event.isTriggerIn(triggers) &amp;&amp; event.isNormalPriority() === normal) {
                event.start();
            }
        });
    }
};

/* 随着输入移动 */
Game_Player.prototype.moveByInput = function() {
    if (!this.isMoving() &amp;&amp; this.canMove()) {
        var direction = this.getInputDirection();
        if (direction &gt; 0) {
            $gameTemp.clearDestination();
        } else if ($gameTemp.isDestinationValid()){
            var x = $gameTemp.destinationX();
            var y = $gameTemp.destinationY();
            direction = this.findDirectionTo(x, y);
        }
        if (direction &gt; 0) {
            this.executeMove(direction);
        }
    }
};

/* 是否可移动 */
Game_Player.prototype.canMove = function() {
    if ($gameMap.isEventRunning() || $gameMessage.isBusy()) {
        return false;
    }
    if (this.isMoveRouteForcing() || this.areFollowersGathering()) {
        return false;
    }
    if (this._vehicleGettingOn || this._vehicleGettingOff) {
        return false;
    }
    if (this.isInVehicle() &amp;&amp; !this.vehicle().canMove()) {
        return false;
    }
    return true;
};

/* 获取输入的方向 */
Game_Player.prototype.getInputDirection = function() {
    return Input.dir4;
};

/* 执行移动 */
Game_Player.prototype.executeMove = function(direction) {
    this.moveStraight(direction);
};

/* 更新 */
Game_Player.prototype.update = function(sceneActive) {
    var lastScrolledX = this.scrolledX();
    var lastScrolledY = this.scrolledY();
    var wasMoving = this.isMoving();
    this.updateDashing();
    if (sceneActive) {
        this.moveByInput();
    }
    Game_Character.prototype.update.call(this);
    this.updateScroll(lastScrolledX, lastScrolledY);
    this.updateVehicle();
    if (!this.isMoving()) {
        this.updateNonmoving(wasMoving);
    }
    this._followers.update();
};

/* 更新奔跑 */
Game_Player.prototype.updateDashing = function() {
    if (this.isMoving()) {
        return;
    }
    if (this.canMove() &amp;&amp; !this.isInVehicle() &amp;&amp; !$gameMap.isDashDisabled()) {
        this._dashing = this.isDashButtonPressed() || $gameTemp.isDestinationValid();
    } else {
        this._dashing = false;
    }
};

/* 是否奔跑按键按下 */
Game_Player.prototype.isDashButtonPressed = function() {
    var shift = Input.isPressed('shift');
    if (ConfigManager.alwaysDash) {
        return !shift;
    } else {
        return shift;
    }
};

/* 更新滚动 */
Game_Player.prototype.updateScroll = function(lastScrolledX, lastScrolledY) {
    var x1 = lastScrolledX;
    var y1 = lastScrolledY;
    var x2 = this.scrolledX();
    var y2 = this.scrolledY();
    if (y2 &gt; y1 &amp;&amp; y2 &gt; this.centerY()) {
        $gameMap.scrollDown(y2 - y1);
    }
    if (x2 &lt; x1 &amp;&amp; x2 &lt; this.centerX()) {
        $gameMap.scrollLeft(x1 - x2);
    }
    if (x2 &gt; x1 &amp;&amp; x2 &gt; this.centerX()) {
        $gameMap.scrollRight(x2 - x1);
    }
    if (y2 &lt; y1 &amp;&amp; y2 &lt; this.centerY()) {
        $gameMap.scrollUp(y1 - y2);
    }
};

/* 更新载具 */
Game_Player.prototype.updateVehicle = function() {
    if (this.isInVehicle() &amp;&amp; !this.areFollowersGathering()) {
        if (this._vehicleGettingOn) {
            this.updateVehicleGetOn();
        } else if (this._vehicleGettingOff) {
            this.updateVehicleGetOff();
        } else {
            this.vehicle().syncWithPlayer();
        }
    }
};

/* 更新上载具 */
Game_Player.prototype.updateVehicleGetOn = function() {
    if (!this.areFollowersGathering() &amp;&amp; !this.isMoving()) {
        this.setDirection(this.vehicle().direction());
        this.setMoveSpeed(this.vehicle().moveSpeed());
        this._vehicleGettingOn = false;
        this.setTransparent(true);
        if (this.isInAirship()) {
            this.setThrough(true);
        }
        this.vehicle().getOn();
    }
};

/* 更新下载具 */
Game_Player.prototype.updateVehicleGetOff = function() {
    if (!this.areFollowersGathering() &amp;&amp; this.vehicle().isLowest()) {
        this._vehicleGettingOff = false;
        this._vehicleType = 'walk';
        this.setTransparent(false);
    }
};

/* 更新不移动 */
Game_Player.prototype.updateNonmoving = function(wasMoving) {
    if (!$gameMap.isEventRunning()) {
        if (wasMoving) {
            $gameParty.onPlayerWalk();
            this.checkEventTriggerHere([1,2]);
            if ($gameMap.setupStartingEvent()) {
                return;
            }
        }
        if (this.triggerAction()) {
            return;
        }
        if (wasMoving) {
            this.updateEncounterCount();
        } else {
            $gameTemp.clearDestination();
        }
    }
};

/* 触发行动 */
Game_Player.prototype.triggerAction = function() {
    if (this.canMove()) {
        if (this.triggerButtonAction()) {
            return true;
        }
        if (this.triggerTouchAction()) {
            return true;
        }
    }
    return false;
};

/* 触发按键行为 */
Game_Player.prototype.triggerButtonAction = function() {
    if (Input.isTriggered('ok')) {
        if (this.getOnOffVehicle()) {
            return true;
        }
        this.checkEventTriggerHere([0]);
        if ($gameMap.setupStartingEvent()) {
            return true;
        }
        this.checkEventTriggerThere([0,1,2]);
        if ($gameMap.setupStartingEvent()) {
            return true;
        }
    }
    return false;
};

/* 触发触摸行为 */
Game_Player.prototype.triggerTouchAction = function() {
    if ($gameTemp.isDestinationValid()){
        var direction = this.direction();
        var x1 = this.x;
        var y1 = this.y;
        var x2 = $gameMap.roundXWithDirection(x1, direction);
        var y2 = $gameMap.roundYWithDirection(y1, direction);
        var x3 = $gameMap.roundXWithDirection(x2, direction);
        var y3 = $gameMap.roundYWithDirection(y2, direction);
        var destX = $gameTemp.destinationX();
        var destY = $gameTemp.destinationY();
        if (destX === x1 &amp;&amp; destY === y1) {
            return this.triggerTouchActionD1(x1, y1);
        } else if (destX === x2 &amp;&amp; destY === y2) {
            return this.triggerTouchActionD2(x2, y2);
        } else if (destX === x3 &amp;&amp; destY === y3) {
            return this.triggerTouchActionD3(x2, y2);
        }
    }
    return false;
};

/* 触发触摸行为 D1 */
Game_Player.prototype.triggerTouchActionD1 = function(x1, y1) {
    if ($gameMap.airship().pos(x1, y1)) {
        if (TouchInput.isTriggered() &amp;&amp; this.getOnOffVehicle()) {
            return true;
        }
    }
    this.checkEventTriggerHere([0]);
    return $gameMap.setupStartingEvent();
};

/* 触发触摸行为 D2 */
Game_Player.prototype.triggerTouchActionD2 = function(x2, y2) {
    if ($gameMap.boat().pos(x2, y2) || $gameMap.ship().pos(x2, y2)) {
        if (TouchInput.isTriggered() &amp;&amp; this.getOnVehicle()) {
            return true;
        }
    }
    if (this.isInBoat() || this.isInShip()) {
        if (TouchInput.isTriggered() &amp;&amp; this.getOffVehicle()) {
            return true;
        }
    }
    this.checkEventTriggerThere([0,1,2]);
    return $gameMap.setupStartingEvent();
};

/* 触发触摸行为 D3 */
Game_Player.prototype.triggerTouchActionD3 = function(x2, y2) {
    if ($gameMap.isCounter(x2, y2)) {
        this.checkEventTriggerThere([0,1,2]);
    }
    return $gameMap.setupStartingEvent();
};

/* 更新遇敌计数 */
Game_Player.prototype.updateEncounterCount = function() {
    if (this.canEncounter()) {
        this._encounterCount -= this.encounterProgressValue();
    }
};

/* 是否能遇敌 */
Game_Player.prototype.canEncounter = function() {
    return (!$gameParty.hasEncounterNone() &amp;&amp; $gameSystem.isEncounterEnabled() &amp;&amp;
            !this.isInAirship() &amp;&amp; !this.isMoveRouteForcing() &amp;&amp; !this.isDebugThrough());
};

/* 遇敌进度值 */
Game_Player.prototype.encounterProgressValue = function() {
    var value = $gameMap.isBush(this.x, this.y) ? 2 : 1;
    if ($gameParty.hasEncounterHalf()) {
        value *= 0.5;
    }
    if (this.isInShip()) {
        value *= 0.5;
    }
    return value;
};

/* 检测这里（玩家位置）的事件触发条件 */
Game_Player.prototype.checkEventTriggerHere = function(triggers) {
    if (this.canStartLocalEvents()) {
        this.startMapEvent(this.x, this.y, triggers, false);
    }
};

/* 检测那里（玩家前方位置）的事件触发条件 */
Game_Player.prototype.checkEventTriggerThere = function(triggers) {
    if (this.canStartLocalEvents()) {
        var direction = this.direction();
        var x1 = this.x;
        var y1 = this.y;
        var x2 = $gameMap.roundXWithDirection(x1, direction);
        var y2 = $gameMap.roundYWithDirection(y1, direction);
        this.startMapEvent(x2, y2, triggers, true);
        if (!$gameMap.isAnyEventStarting() &amp;&amp; $gameMap.isCounter(x2, y2)) {
            var x3 = $gameMap.roundXWithDirection(x2, direction);
            var y3 = $gameMap.roundYWithDirection(y2, direction);
            this.startMapEvent(x3, y3, triggers, true);
        }
    }
};

/* 检测接触的事件触发条件 */
Game_Player.prototype.checkEventTriggerTouch = function(x, y) {
    if (this.canStartLocalEvents()) {
        this.startMapEvent(x, y, [1,2], true);
    }
};

/* 是否能开始本地事件 */
Game_Player.prototype.canStartLocalEvents = function() {
    return !this.isInAirship();
};

/* 上下载具 */
Game_Player.prototype.getOnOffVehicle = function() {
    if (this.isInVehicle()) {
        return this.getOffVehicle();
    } else {
        return this.getOnVehicle();
    }
};

/* 上载具 */
Game_Player.prototype.getOnVehicle = function() {
    var direction = this.direction();
    var x1 = this.x;
    var y1 = this.y;
    var x2 = $gameMap.roundXWithDirection(x1, direction);
    var y2 = $gameMap.roundYWithDirection(y1, direction);
    if ($gameMap.airship().pos(x1, y1)) {
        this._vehicleType = 'airship';
    } else if ($gameMap.ship().pos(x2, y2)) {
        this._vehicleType = 'ship';
    } else if ($gameMap.boat().pos(x2, y2)) {
        this._vehicleType = 'boat';
    }
    if (this.isInVehicle()) {
        this._vehicleGettingOn = true;
        if (!this.isInAirship()) {
            this.forceMoveForward();
        }
        this.gatherFollowers();
    }
    return this._vehicleGettingOn;
};

/* 下载具 */
Game_Player.prototype.getOffVehicle = function() {
    if (this.vehicle().isLandOk(this.x, this.y, this.direction())) {
        if (this.isInAirship()) {
            this.setDirection(2);
        }
        this._followers.synchronize(this.x, this.y, this.direction());
        this.vehicle().getOff();
        if (!this.isInAirship()) {
            this.forceMoveForward();
            this.setTransparent(false);
        }
        this._vehicleGettingOff = true;
        this.setMoveSpeed(4);
        this.setThrough(false);
        this.makeEncounterCount();
        this.gatherFollowers();
    }
    return this._vehicleGettingOff;
};

/* 强制向前移动 */
Game_Player.prototype.forceMoveForward = function() {
    this.setThrough(true);
    this.moveForward();
    this.setThrough(false);
};

/* 是否在有害地形 */
Game_Player.prototype.isOnDamageFloor = function() {
    return $gameMap.isDamageFloor(this.x, this.y) &amp;&amp; !this.isInAirship();
};

/* 直线移动 */
Game_Player.prototype.moveStraight = function(d) {
    if (this.canPass(this.x, this.y, d)) {
        this._followers.updateMove();
    }
    Game_Character.prototype.moveStraight.call(this, d);
};

/* 斜线移动 */
Game_Player.prototype.moveDiagonally = function(horz, vert) {
    if (this.canPassDiagonally(this.x, this.y, horz, vert)) {
        this._followers.updateMove();
    }
    Game_Character.prototype.moveDiagonally.call(this, horz, vert);
};

/* 跳跃 */
Game_Player.prototype.jump = function(xPlus, yPlus) {
    Game_Character.prototype.jump.call(this, xPlus, yPlus);
    this._followers.jumpAll();
};

/* 显示跟随者 */
Game_Player.prototype.showFollowers = function() {
    this._followers.show();
};

/* 隐藏跟随者 */
Game_Player.prototype.hideFollowers = function() {
    this._followers.hide();
};

/* 集合跟随者 */
Game_Player.prototype.gatherFollowers = function() {
    this._followers.gather();
};

/* 是否跟随者集合中 */
Game_Player.prototype.areFollowersGathering = function() {
    return this._followers.areGathering();
};

/* 是否跟随者集合了 */
Game_Player.prototype.areFollowersGathered = function() {
    return this._followers.areGathered();
};

//-----------------------------------------------------------------------------
// 游戏_跟随者
// Game_Follower
//
// 跟随者的游戏对象类。
// The game object class for a follower. A follower is an allied character,
// other than the front character, displayed in the party.

function Game_Follower() {
    this.initialize.apply(this, arguments);
}

Game_Follower.prototype = Object.create(Game_Character.prototype);
Game_Follower.prototype.constructor = Game_Follower;

/* 初始化 */
Game_Follower.prototype.initialize = function(memberIndex) {
    Game_Character.prototype.initialize.call(this);
    this._memberIndex = memberIndex;
    this.setTransparent($dataSystem.optTransparent);
    this.setThrough(true);
};

/* 刷新 */
Game_Follower.prototype.refresh = function() {
    var characterName = this.isVisible() ? this.actor().characterName() : '';
    var characterIndex = this.isVisible() ? this.actor().characterIndex() : 0;
    this.setImage(characterName, characterIndex);
};

/* 角色 */
Game_Follower.prototype.actor = function() {
    return $gameParty.battleMembers()[this._memberIndex];
};

/* 是否可见的 */
Game_Follower.prototype.isVisible = function() {
    return this.actor() &amp;&amp; $gamePlayer.followers().isVisible();
};

/* 更新 */
Game_Follower.prototype.update = function() {
    Game_Character.prototype.update.call(this);
    this.setMoveSpeed($gamePlayer.realMoveSpeed());
    this.setOpacity($gamePlayer.opacity());
    this.setBlendMode($gamePlayer.blendMode());
    this.setWalkAnime($gamePlayer.hasWalkAnime());
    this.setStepAnime($gamePlayer.hasStepAnime());
    this.setDirectionFix($gamePlayer.isDirectionFixed());
    this.setTransparent($gamePlayer.isTransparent());
};

/* 追逐人物 */
Game_Follower.prototype.chaseCharacter = function(character) {
    var sx = this.deltaXFrom(character.x);
    var sy = this.deltaYFrom(character.y);
    if (sx !== 0 &amp;&amp; sy !== 0) {
        this.moveDiagonally(sx &gt; 0 ? 4 : 6, sy &gt; 0 ? 8 : 2);
    } else if (sx !== 0) {
        this.moveStraight(sx &gt; 0 ? 4 : 6);
    } else if (sy !== 0) {
        this.moveStraight(sy &gt; 0 ? 8 : 2);
    }
    this.setMoveSpeed($gamePlayer.realMoveSpeed());
};

//-----------------------------------------------------------------------------
// 游戏_跟随者们 
// Game_Followers
//
// 跟随者数组的封装类。 
// The wrapper class for a follower array.

function Game_Followers() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_Followers.prototype.initialize = function() {
    this._visible = $dataSystem.optFollowers;
    this._gathering = false;
    this._data = [];
    for (var i = 1; i &lt; $gameParty.maxBattleMembers(); i) {
        this._data.push(new Game_Follower(i));
    }
};

/* 是否可见的 */
Game_Followers.prototype.isVisible = function() {
    return this._visible;
};

/* 显示 */
Game_Followers.prototype.show = function() {
    this._visible = true;
};

/* 隐藏 */
Game_Followers.prototype.hide = function() {
    this._visible = false;
};

/* 跟随者 */
Game_Followers.prototype.follower = function(index) {
    return this._data[index];
};

/* 遍历每个 */
Game_Followers.prototype.forEach = function(callback, thisObject) {
    this._data.forEach(callback, thisObject);
};

/* 翻转每个 */
Game_Followers.prototype.reverseEach = function(callback, thisObject) {
    this._data.reverse();
    this._data.forEach(callback, thisObject);
    this._data.reverse();
};

/* 刷新 */
Game_Followers.prototype.refresh = function() {
    this.forEach(function(follower) {
        return follower.refresh();
    }, this);
};

/* 更新 */
Game_Followers.prototype.update = function() {
    if (this.areGathering()) {
        if (!this.areMoving()) {
            this.updateMove();
        }
        if (this.areGathered()) {
            this._gathering = false;
        }
    }
    this.forEach(function(follower) {
        follower.update();
    }, this);
};

/* 更新移动 */
Game_Followers.prototype.updateMove = function() {
    for (var i = this._data.length - 1; i &gt;= 0; i--) {
        var precedingCharacter = (i &gt; 0 ? this._data[i - 1] : $gamePlayer);
        this._data[i].chaseCharacter(precedingCharacter);
    }
};

/* 所有跳跃 */
Game_Followers.prototype.jumpAll = function() {
    if ($gamePlayer.isJumping()) {
        for (var i = 0; i &lt; this._data.length; i) {
            var follower = this._data[i];
            var sx = $gamePlayer.deltaXFrom(follower.x);
            var sy = $gamePlayer.deltaYFrom(follower.y);
            follower.jump(sx, sy);
        }
    }
};

/* 同步 */
Game_Followers.prototype.synchronize = function(x, y, d) {
    this.forEach(function(follower) {
        follower.locate(x, y);
        follower.setDirection(d);
    }, this);
};

/* 集合 */
Game_Followers.prototype.gather = function() {
    this._gathering = true;
};

/* 是否集合中 */
Game_Followers.prototype.areGathering = function() {
    return this._gathering;
};

/* 可见的跟随者 */
Game_Followers.prototype.visibleFollowers = function() {
    return this._data.filter(function(follower) {
        return follower.isVisible();
    }, this);
};

/* 是否移动中 */
Game_Followers.prototype.areMoving = function() {
    return this.visibleFollowers().some(function(follower) {
        return follower.isMoving();
    }, this);
};

/* 是否集合了 */
Game_Followers.prototype.areGathered = function() {
    return this.visibleFollowers().every(function(follower) {
        return !follower.isMoving() &amp;&amp; follower.pos($gamePlayer.x, $gamePlayer.y);
    }, this);
};

/* 是否有人碰撞 */
Game_Followers.prototype.isSomeoneCollided = function(x, y) {
    return this.visibleFollowers().some(function(follower) {
        return follower.pos(x, y);
    }, this);
};

//-----------------------------------------------------------------------------
// 游戏_载具 
// Game_Vehicle
//
// 载具的游戏对象类。 
// The game object class for a vehicle.

function Game_Vehicle() {
    this.initialize.apply(this, arguments);
}

Game_Vehicle.prototype = Object.create(Game_Character.prototype);
Game_Vehicle.prototype.constructor = Game_Vehicle;

/* 初始化 */
Game_Vehicle.prototype.initialize = function(type) {
    Game_Character.prototype.initialize.call(this);
    this._type = type;
    this.resetDirection();
    this.initMoveSpeed();
    this.loadSystemSettings();
};

/* 初始化成员 */
Game_Vehicle.prototype.initMembers = function() {
    Game_Character.prototype.initMembers.call(this);
    this._type = '';
    this._mapId = 0;
    this._altitude = 0;
    this._driving = false;
    this._bgm = null;
};

/* 是否是小舟 */
Game_Vehicle.prototype.isBoat = function() {
    return this._type === 'boat';
};

/* 是否是大船 */
Game_Vehicle.prototype.isShip = function() {
    return this._type === 'ship';
};

/* 是否是飞艇 */
Game_Vehicle.prototype.isAirship = function() {
    return this._type === 'airship';
};

/* 重置方向 */
Game_Vehicle.prototype.resetDirection = function() {
    this.setDirection(4);
};

/* 初始化移动速度 */
Game_Vehicle.prototype.initMoveSpeed = function() {
    if (this.isBoat()) {
        this.setMoveSpeed(4);
    } else if (this.isShip()) {
        this.setMoveSpeed(5);
    } else if (this.isAirship()) {
        this.setMoveSpeed(6);
    }
};

/* 载具 */
Game_Vehicle.prototype.vehicle = function() {
    if (this.isBoat()) {
        return $dataSystem.boat;
    } else if (this.isShip()) {
        return $dataSystem.ship;
    } else if (this.isAirship()) {
        return $dataSystem.airship;
    } else {
        return null;
    }
};

/* 读取系统设置 */
Game_Vehicle.prototype.loadSystemSettings = function() {
    var vehicle = this.vehicle();
    this._mapId = vehicle.startMapId;
    this.setPosition(vehicle.startX, vehicle.startY);
    this.setImage(vehicle.characterName, vehicle.characterIndex);
};

/* 刷新 */
Game_Vehicle.prototype.refresh = function() {
    if (this._driving) {
        this._mapId = $gameMap.mapId();
        this.syncWithPlayer();
    } else if (this._mapId === $gameMap.mapId()) {
        this.locate(this.x, this.y);
    }
    if (this.isAirship()) {
        this.setPriorityType(this._driving ? 2 : 0);
    } else {
        this.setPriorityType(1);
    }
    this.setWalkAnime(this._driving);
    this.setStepAnime(this._driving);
    this.setTransparent(this._mapId !== $gameMap.mapId());
};

/* 设置位置 */
Game_Vehicle.prototype.setLocation = function(mapId, x, y) {
    this._mapId = mapId;
    this.setPosition(x, y);
    this.refresh();
};

/* 位置 */
Game_Vehicle.prototype.pos = function(x, y) {
    if (this._mapId === $gameMap.mapId()) {
        return Game_Character.prototype.pos.call(this, x, y);
    } else {
        return false;
    }
};

/* 是否地图可通行 */
Game_Vehicle.prototype.isMapPassable = function(x, y, d) {
    var x2 = $gameMap.roundXWithDirection(x, d);
    var y2 = $gameMap.roundYWithDirection(y, d);
    if (this.isBoat()) {
        return $gameMap.isBoatPassable(x2, y2);
    } else if (this.isShip()) {
        return $gameMap.isShipPassable(x2, y2);
    } else if (this.isAirship()) {
        return true;
    } else {
        return false;
    }
};

/* 上 */
Game_Vehicle.prototype.getOn = function() {
    this._driving = true;
    this.setWalkAnime(true);
    this.setStepAnime(true);
    $gameSystem.saveWalkingBgm();
    this.playBgm();
};

/* 下 */
Game_Vehicle.prototype.getOff = function() {
    this._driving = false;
    this.setWalkAnime(false);
    this.setStepAnime(false);
    this.resetDirection();
    $gameSystem.replayWalkingBgm();
};

/* 设置 BGM */
Game_Vehicle.prototype.setBgm = function(bgm) {
    this._bgm = bgm;
};

/* 播放 BGM */
Game_Vehicle.prototype.playBgm = function() {
    AudioManager.playBgm(this._bgm || this.vehicle().bgm);
};

/* 同步玩家 */
Game_Vehicle.prototype.syncWithPlayer = function() {
    this.copyPosition($gamePlayer);
    this.refreshBushDepth();
};

/* 画面 Y 坐标 */
Game_Vehicle.prototype.screenY = function() {
    return Game_Character.prototype.screenY.call(this) - this._altitude;
};

/* 影子 X 坐标 */
Game_Vehicle.prototype.shadowX = function() {
    return this.screenX();
};

/* 影子 Y 坐标 */
Game_Vehicle.prototype.shadowY = function() {
    return this.screenY() + this._altitude;
};

/* 影子不透明度 */
Game_Vehicle.prototype.shadowOpacity = function() {
    return 255 * this._altitude / this.maxAltitude();
};

/* 是否可移动 */
Game_Vehicle.prototype.canMove = function() {
    if (this.isAirship()) {
        return this.isHighest();
    } else {
        return true;
    }
};

/* 更新 */
Game_Vehicle.prototype.update = function() {
    Game_Character.prototype.update.call(this);
    if (this.isAirship()) {
        this.updateAirship();
    }
};

/* 更新飞艇 */
Game_Vehicle.prototype.updateAirship = function() {
    this.updateAirshipAltitude();
    this.setStepAnime(this.isHighest());
    this.setPriorityType(this.isLowest() ? 0 : 2);
};

/* 更新飞艇高度 */
Game_Vehicle.prototype.updateAirshipAltitude = function() {
    if (this._driving &amp;&amp; !this.isHighest()) {
        this._altitude;
    }
    if (!this._driving &amp;&amp; !this.isLowest()) {
        this._altitude--;
    }
};

/* 最大高度 */
Game_Vehicle.prototype.maxAltitude = function() {
    return 48;
};

/* 是否最低 */
Game_Vehicle.prototype.isLowest = function() {
    return this._altitude &lt;= 0;
};

/* 是否最高 */
Game_Vehicle.prototype.isHighest = function() {
    return this._altitude &gt;= this.maxAltitude();
};

/* 是否可以起飞 */
Game_Vehicle.prototype.isTakeoffOk = function() {
    return $gamePlayer.areFollowersGathered();
};

/* 是否陆地可下载具 */
Game_Vehicle.prototype.isLandOk = function(x, y, d) {
    if (this.isAirship()) {
        if (!$gameMap.isAirshipLandOk(x, y)) {
            return false;
        }
        if ($gameMap.eventsXy(x, y).length &gt; 0) {
            return false;
        }
    } else {
        var x2 = $gameMap.roundXWithDirection(x, d);
        var y2 = $gameMap.roundYWithDirection(y, d);
        if (!$gameMap.isValid(x2, y2)) {
            return false;
        }
        if (!$gameMap.isPassable(x2, y2, this.reverseDir(d))) {
            return false;
        }
        if (this.isCollidedWithCharacters(x2, y2)) {
            return false;
        }
    }
    return true;
};

//-----------------------------------------------------------------------------
// 游戏_事件 
// Game_Event
//
// 事件的游戏对象类。它包含用于事件页切换和运行并行处理事件的功能。 
// The game object class for an event. It contains functionality for event page
// switching and running parallel process events.

function Game_Event() {
    this.initialize.apply(this, arguments);
}

Game_Event.prototype = Object.create(Game_Character.prototype);
Game_Event.prototype.constructor = Game_Event;

/* 初始化 */
Game_Event.prototype.initialize = function(mapId, eventId) {
    Game_Character.prototype.initialize.call(this);
    this._mapId = mapId;
    this._eventId = eventId;
    this.locate(this.event().x, this.event().y);
    this.refresh();
};

/* 初始化成员 */
Game_Event.prototype.initMembers = function() {
    Game_Character.prototype.initMembers.call(this);
    this._moveType = 0;
    this._trigger = 0;
    this._starting = false;
    this._erased = false;
    this._pageIndex = -2;
    this._originalPattern = 1;
    this._originalDirection = 2;
    this._prelockDirection = 0;
    this._locked = false;
};

/* 事件 ID */
Game_Event.prototype.eventId = function() {
    return this._eventId;
};

/* 事件 */
Game_Event.prototype.event = function() {
    return $dataMap.events[this._eventId];
};

/* 页 */
Game_Event.prototype.page = function() {
    return this.event().pages[this._pageIndex];
};

/* 列表 */
Game_Event.prototype.list = function() {
    return this.page().list;
};

/* 是否和人物（事件、载具和玩家）碰撞 */
Game_Event.prototype.isCollidedWithCharacters = function(x, y) {
    return (Game_Character.prototype.isCollidedWithCharacters.call(this, x, y) ||
            this.isCollidedWithPlayerCharacters(x, y));
};

/* 是否和事件碰撞 */
Game_Event.prototype.isCollidedWithEvents = function(x, y) {
    var events = $gameMap.eventsXyNt(x, y);
    return events.length &gt; 0;
};

/* 是否和玩家碰撞 */
Game_Event.prototype.isCollidedWithPlayerCharacters = function(x, y) {
    return this.isNormalPriority() &amp;&amp; $gamePlayer.isCollided(x, y);
};

/* 锁定 */
Game_Event.prototype.lock = function() {
    if (!this._locked) {
        this._prelockDirection = this.direction();
        this.turnTowardPlayer();
        this._locked = true;
    }
};

/* 解锁 */
Game_Event.prototype.unlock = function() {
    if (this._locked) {
        this._locked = false;
        this.setDirection(this._prelockDirection);
    }
};

/* 更新停止 */
Game_Event.prototype.updateStop = function() {
    if (this._locked) {
        this.resetStopCount();
    }
    Game_Character.prototype.updateStop.call(this);
    if (!this.isMoveRouteForcing()) {
        this.updateSelfMovement();
    }
};

/* 更新自身移动 */
Game_Event.prototype.updateSelfMovement = function() {
    if (!this._locked &amp;&amp; this.isNearTheScreen() &amp;&amp;
            this.checkStop(this.stopCountThreshold())) {
        switch (this._moveType) {
        case 1:
            this.moveTypeRandom();
            break;
        case 2:
            this.moveTypeTowardPlayer();
            break;
        case 3:
            this.moveTypeCustom();
            break;
        }
    }
};

/* 停止计数的阈值 */
Game_Event.prototype.stopCountThreshold = function() {
    return 30 * (5 - this.moveFrequency());
};

/* 移动类型随机 */
Game_Event.prototype.moveTypeRandom = function() {
    switch (Math.randomInt(6)) {
    case 0: case 1:
        this.moveRandom();
        break;
    case 2: case 3: case 4:
        this.moveForward();
        break;
    case 5:
        this.resetStopCount();
        break;
    }
};

/* 移动类型朝向玩家 */
Game_Event.prototype.moveTypeTowardPlayer = function() {
    if (this.isNearThePlayer()) {
        switch (Math.randomInt(6)) {
        case 0: case 1: case 2: case 3:
            this.moveTowardPlayer();
            break;
        case 4:
            this.moveRandom();
            break;
        case 5:
            this.moveForward();
            break;
        }
    } else {
        this.moveRandom();
    }
};

/* 是否在玩家附近 */
Game_Event.prototype.isNearThePlayer = function() {
    var sx = Math.abs(this.deltaXFrom($gamePlayer.x));
    var sy = Math.abs(this.deltaYFrom($gamePlayer.y));
    return sx + sy &lt; 20;
};

/* 移动类型自定义 */
Game_Event.prototype.moveTypeCustom = function() {
    this.updateRoutineMove();
};

/* 是否开始 */
Game_Event.prototype.isStarting = function() {
    return this._starting;
};

/* 清除开始标志 */
Game_Event.prototype.clearStartingFlag = function() {
    this._starting = false;
};

/* 是否触发条件在其中 */
Game_Event.prototype.isTriggerIn = function(triggers) {
    return triggers.contains(this._trigger);
};

/* 开始 */
Game_Event.prototype.start = function() {
    var list = this.list();
    if (list &amp;&amp; list.length &gt; 1) {
        this._starting = true;
        if (this.isTriggerIn([0,1,2])) {
            this.lock();
        }
    }
};

/* 消除 */
Game_Event.prototype.erase = function() {
    this._erased = true;
    this.refresh();
};

/* 刷新 */
Game_Event.prototype.refresh = function() {
    var newPageIndex = this._erased ? -1 : this.findProperPageIndex();
    if (this._pageIndex !== newPageIndex) {
        this._pageIndex = newPageIndex;
        this.setupPage();
    }
};

/* 寻找适当的页面索引 */
Game_Event.prototype.findProperPageIndex = function() {
    var pages = this.event().pages;
    for (var i = pages.length - 1; i &gt;= 0; i--) {
        var page = pages[i];
        if (this.meetsConditions(page)) {
            return i;
        }
    }
    return -1;
};

/* 是否满足条件 */
Game_Event.prototype.meetsConditions = function(page) {
    var c = page.conditions;
    if (c.switch1Valid) {
        if (!$gameSwitches.value(c.switch1Id)) {
            return false;
        }
    }
    if (c.switch2Valid) {
        if (!$gameSwitches.value(c.switch2Id)) {
            return false;
        }
    }
    if (c.variableValid) {
        if ($gameVariables.value(c.variableId) &lt; c.variableValue) {
            return false;
        }
    }
    if (c.selfSwitchValid) {
        var key = [this._mapId, this._eventId, c.selfSwitchCh];
        if ($gameSelfSwitches.value(key) !== true) {
            return false;
        }
    }
    if (c.itemValid) {
        var item = $dataItems[c.itemId];
        if (!$gameParty.hasItem(item)) {
            return false;
        }
    }
    if (c.actorValid) {
        var actor = $gameActors.actor(c.actorId);
        if (!$gameParty.members().contains(actor)) {
            return false;
        }
    }
    return true;
};

/* 设置页面 */
Game_Event.prototype.setupPage = function() {
    if (this._pageIndex &gt;= 0) {
        this.setupPageSettings();
    } else {
        this.clearPageSettings();
    }
    this.refreshBushDepth();
    this.clearStartingFlag();
    this.checkEventTriggerAuto();
};

/* 清除页面设置 */
Game_Event.prototype.clearPageSettings = function() {
    this.setImage('', 0);
    this._moveType = 0;
    this._trigger = null;
    this._interpreter = null;
    this.setThrough(true);
};

/* 设置页面设置 */
Game_Event.prototype.setupPageSettings = function() {
    var page = this.page();
    var image = page.image;
    if (image.tileId &gt; 0) {
        this.setTileImage(image.tileId);
    } else {
        this.setImage(image.characterName, image.characterIndex);
    }
    if (this._originalDirection !== image.direction) {
        this._originalDirection = image.direction;
        this._prelockDirection = 0;
        this.setDirectionFix(false);
        this.setDirection(image.direction);
    }
    if (this._originalPattern !== image.pattern) {
        this._originalPattern = image.pattern;
        this.setPattern(image.pattern);
    }
    this.setMoveSpeed(page.moveSpeed);
    this.setMoveFrequency(page.moveFrequency);
    this.setPriorityType(page.priorityType);
    this.setWalkAnime(page.walkAnime);
    this.setStepAnime(page.stepAnime);
    this.setDirectionFix(page.directionFix);
    this.setThrough(page.through);
    this.setMoveRoute(page.moveRoute);
    this._moveType = page.moveType;
    this._trigger = page.trigger;
    if (this._trigger === 4) {
        this._interpreter = new Game_Interpreter();
    } else {
        this._interpreter = null;
    }
};

/* 是否起始图案 */
Game_Event.prototype.isOriginalPattern = function() {
    return this.pattern() === this._originalPattern;
};

/* 重置图案 */
Game_Event.prototype.resetPattern = function() {
    this.setPattern(this._originalPattern);
};

/* 检测接触的事件触发条件 */
Game_Event.prototype.checkEventTriggerTouch = function(x, y) {
    if (!$gameMap.isEventRunning()) {
        if (this._trigger === 2 &amp;&amp; $gamePlayer.pos(x, y)) {
            if (!this.isJumping() &amp;&amp; this.isNormalPriority()) {
                this.start();
            }
        }
    }
};

/* 检测自动执行的事件触发条件 */
Game_Event.prototype.checkEventTriggerAuto = function() {
    if (this._trigger === 3) {
        this.start();
    }
};

/* 更新 */
Game_Event.prototype.update = function() {
    Game_Character.prototype.update.call(this);
    this.checkEventTriggerAuto();
    this.updateParallel();
};

/* 更新并行 */
Game_Event.prototype.updateParallel = function() {
    if (this._interpreter) {
        if (!this._interpreter.isRunning()) {
            this._interpreter.setup(this.list(), this._eventId);
        }
        this._interpreter.update();
    }
};

/* 放置 */
Game_Event.prototype.locate = function(x, y) {
    Game_Character.prototype.locate.call(this, x, y);
    this._prelockDirection = 0;
};

/* 强制移动路线 */
Game_Event.prototype.forceMoveRoute = function(moveRoute) {
    Game_Character.prototype.forceMoveRoute.call(this, moveRoute);
    this._prelockDirection = 0;
};

//-----------------------------------------------------------------------------
// 游戏_解释器 
// Game_Interpreter
//
// 运行事件指令的解释器。 
// The interpreter for running event commands.

function Game_Interpreter() {
    this.initialize.apply(this, arguments);
}

/* 初始化 */
Game_Interpreter.prototype.initialize = function(depth) {
    this._depth = depth || 0;
    this.checkOverflow();
    this.clear();
    this._branch = {};
    this._params = [];
    this._indent = 0;
    this._frameCount = 0;
    this._freezeChecker = 0;
};

/* 检测溢出 */
Game_Interpreter.prototype.checkOverflow = function() {
    if (this._depth &gt;= 100) {
        throw new Error('Common event calls exceeded the limit');
    }
};

/* 清除 */
Game_Interpreter.prototype.clear = function() {
    this._mapId = 0;
    this._eventId = 0;
    this._list = null;
    this._index = 0;
    this._waitCount = 0;
    this._waitMode = '';
    this._comments = '';
    this._character = null;
    this._childInterpreter = null;
};

/* 设置 */
Game_Interpreter.prototype.setup = function(list, eventId) {
    this.clear();
    this._mapId = $gameMap.mapId();
    this._eventId = eventId || 0;
    this._list = list;
    Game_Interpreter.requestImages(list);
};

/* 事件 ID */
Game_Interpreter.prototype.eventId = function() {
    return this._eventId;
};

/* 是否在当前地图 */
Game_Interpreter.prototype.isOnCurrentMap = function() {
    return this._mapId === $gameMap.mapId();
};

/* 设置储存的公共事件 */
Game_Interpreter.prototype.setupReservedCommonEvent = function() {
    if ($gameTemp.isCommonEventReserved()) {
        this.setup($gameTemp.reservedCommonEvent().list);
        $gameTemp.clearCommonEvent();
        return true;
    } else {
        return false;
    }
};

/* 是否运行 */
Game_Interpreter.prototype.isRunning = function() {
    return !!this._list;
};

/* 更新 */
Game_Interpreter.prototype.update = function() {
    while (this.isRunning()) {
        if (this.updateChild() || this.updateWait()) {
            break;
        }
        if (SceneManager.isSceneChanging()) {
            break;
        }
        if (!this.executeCommand()) {
            break;
        }
        if (this.checkFreeze()) {
            break;
        }
    }
};

/* 更新子解释器 */
Game_Interpreter.prototype.updateChild = function() {
    if (this._childInterpreter) {
        this._childInterpreter.update();
        if (this._childInterpreter.isRunning()) {
            return true;
        } else {
            this._childInterpreter = null;
        }
    }
    return false;
};

/* 更新等待 */
Game_Interpreter.prototype.updateWait = function() {
    return this.updateWaitCount() || this.updateWaitMode();
};

/* 更新等待计数 */
Game_Interpreter.prototype.updateWaitCount = function() {
    if (this._waitCount &gt; 0) {
        this._waitCount--;
        return true;
    }
    return false;
};

/* 更新等待模式 */
Game_Interpreter.prototype.updateWaitMode = function() {
    var waiting = false;
    switch (this._waitMode) {
    case 'message':
        waiting = $gameMessage.isBusy();
        break;
    case 'transfer':
        waiting = $gamePlayer.isTransferring();
        break;
    case 'scroll':
        waiting = $gameMap.isScrolling();
        break;
    case 'route':
        waiting = this._character.isMoveRouteForcing();
        break;
    case 'animation':
        waiting = this._character.isAnimationPlaying();
        break;
    case 'balloon':
        waiting = this._character.isBalloonPlaying();
        break;
    case 'gather':
        waiting = $gamePlayer.areFollowersGathering();
        break;
    case 'action':
        waiting = BattleManager.isActionForced();
        break;
    case 'video':
        waiting = Graphics.isVideoPlaying();
        break;
    case 'image':
        waiting = !ImageManager.isReady();
        break;
    }
    if (!waiting) {
        this._waitMode = '';
    }
    return waiting;
};

/* 设置等待模式 */
Game_Interpreter.prototype.setWaitMode = function(waitMode) {
    this._waitMode = waitMode;
};

/* 等待 */
Game_Interpreter.prototype.wait = function(duration) {
    this._waitCount = duration;
};

/* 渐变速度 */
Game_Interpreter.prototype.fadeSpeed = function() {
    return 24;
};

/* 执行指令 */
Game_Interpreter.prototype.executeCommand = function() {
    var command = this.currentCommand();
    if (command) {
        this._params = command.parameters;
        this._indent = command.indent;
        var methodName = 'command' + command.code;
        if (typeof this[methodName] === 'function') {
            if (!this[methodName]()) {
                return false;
            }
        }
        this._index;
    } else {
        this.terminate();
    }
    return true;
};

/* 检测冻结 */
Game_Interpreter.prototype.checkFreeze = function() {
    if (this._frameCount !== Graphics.frameCount) {
        this._frameCount = Graphics.frameCount;
        this._freezeChecker = 0;
    }
    if (this._freezeChecker &gt;= 100000) {
        return true;
    } else {
        return false;
    }
};

/* 结束 */
Game_Interpreter.prototype.terminate = function() {
    this._list = null;
    this._comments = '';
};

/* 跳出分支 */
Game_Interpreter.prototype.skipBranch = function() {
    while (this._list[this._index + 1].indent &gt; this._indent) {
        this._index;
    }
};

/* 当前指令 */
Game_Interpreter.prototype.currentCommand = function() {
    return this._list[this._index];
};

/* 下一个事件码 */
Game_Interpreter.prototype.nextEventCode = function() {
    var command = this._list[this._index + 1];
    if (command) {
        return command.code;
    } else {
        return 0;
    }
};

/* 循环遍历角色 ID */
Game_Interpreter.prototype.iterateActorId = function(param, callback) {
    if (param === 0) {
        $gameParty.members().forEach(callback);
    } else {
        var actor = $gameActors.actor(param);
        if (actor) {
            callback(actor);
        }
    }
};
/* 循环遍历角色 ID 扩展*/
Game_Interpreter.prototype.iterateActorEx = function(param1, param2, callback) {
    if (param1 === 0) {
        this.iterateActorId(param2, callback);
    } else {
        this.iterateActorId($gameVariables.value(param2), callback);
    }
};

/* 循环遍历角色索引 */
Game_Interpreter.prototype.iterateActorIndex = function(param, callback) {
    if (param &lt; 0) {
        $gameParty.members().forEach(callback);
    } else {
        var actor = $gameParty.members()[param];
        if (actor) {
            callback(actor);
        }
    }
};

/* 循环遍历敌人索引 */
Game_Interpreter.prototype.iterateEnemyIndex = function(param, callback) {
    if (param &lt; 0) {
        $gameTroop.members().forEach(callback);
    } else {
        var enemy = $gameTroop.members()[param];
        if (enemy) {
            callback(enemy);
        }
    }
};

/* 循环遍历战斗者 */
Game_Interpreter.prototype.iterateBattler = function(param1, param2, callback) {
    if ($gameParty.inBattle()) {
        if (param1 === 0) {
            this.iterateEnemyIndex(param2, callback);
        } else {
            this.iterateActorId(param2, callback);
        }
    }
};

/* 人物 */
Game_Interpreter.prototype.character = function(param) {
    if ($gameParty.inBattle()) {
        return null;
    } else if (param &lt; 0) {
        return $gamePlayer;
    } else if (this.isOnCurrentMap()) {
        return $gameMap.event(param &gt; 0 ? param : this._eventId);
    } else {
        return null;
    }
};

/* 操作值 
 * @param {Number} operation 操作（0：增加，1：减少）
 * @param {Number} operandType 操作数类型（0：常量，1：变量）
 * @param {Number} operand 操作数
 */
Game_Interpreter.prototype.operateValue = function(operation, operandType, operand) {
    var value = operandType === 0 ? operand : $gameVariables.value(operand);
    return operation === 0 ? value : -value;
};

/* 改变 HP */
Game_Interpreter.prototype.changeHp = function(target, value, allowDeath) {
    if (target.isAlive()) {
        if (!allowDeath &amp;&amp; target.hp &lt;= -value) {
            value = 1 - target.hp;
        }
        target.gainHp(value);
        if (target.isDead()) {
            target.performCollapse();
        }
    }
};

/* 显示文字 
 * @param {String} _params[0] 脸图名
 * @param {Number} _params[1] 脸图索引
 * @param {Number} _params[2] 背景（0：窗口，1：暗淡，2：透明）
 * @param {Number} _params[3] 窗口位置（0：顶部，1：中间，2：底部）
 */
// Show Text
Game_Interpreter.prototype.command101 = function() {
    if (!$gameMessage.isBusy()) {
        $gameMessage.setFaceImage(this._params[0], this._params[1]);
        $gameMessage.setBackground(this._params[2]);
        $gameMessage.setPositionType(this._params[3]);
        while (this.nextEventCode() === 401) {  // 文本数据（Text data） 
            this._index;
            $gameMessage.add(this.currentCommand().parameters[0]);
        }
        switch (this.nextEventCode()) {
        case 102:  // 显示选项（Show Choices） 
            this._index;
            this.setupChoices(this.currentCommand().parameters);
            break;
        case 103:  // 数值输入处理（Input Number） 
            this._index;
            this.setupNumInput(this.currentCommand().parameters);
            break;
        case 104:  // 物品选择处理（Select Item） 
            this._index;
            this.setupItemChoice(this.currentCommand().parameters);
            break;
        }
        this._index;
        this.setWaitMode('message');
    }
    return false;
};

/* 显示选项 
 * @param {String} _params[0][n] 选项 
 * @param {Number} _params[1] 取消（-2：分支，-1：不允许，0：选项 #1，1：选项 #2，2：选项 #3，3：选项 #4，4：选项 #5，5：选项 #6） 
 * @param {Number} _params[2] 默认（-1：无，0：选项 #1，1：选项 #2，2：选项 #3，3：选项 #4，4：选项 #5，5：选项 #6）  
 * @param {Number} _params[3] 窗口位置（0：左侧，1：中间，2：右侧）
 * @param {Number} _params[4] 背景（0：窗口，1：暗淡，2：透明） 
 */
// Show Choices
Game_Interpreter.prototype.command102 = function() {
    if (!$gameMessage.isBusy()) {
        this.setupChoices(this._params);
        this._index;
        this.setWaitMode('message');
    }
    return false;
};

/* 设置选项 */
Game_Interpreter.prototype.setupChoices = function(params) {
    var choices = params[0].clone();
    var cancelType = params[1];
    var defaultType = params.length &gt; 2 ? params[2] : 0;
    var positionType = params.length &gt; 3 ? params[3] : 2;
    var background = params.length &gt; 4 ? params[4] : 0;
    if (cancelType &gt;= choices.length) {
        cancelType = -2;
    }
    $gameMessage.setChoices(choices, defaultType, cancelType);
    $gameMessage.setChoiceBackground(background);
    $gameMessage.setChoicePositionType(positionType);
    $gameMessage.setChoiceCallback(function(n) {
        this._branch[this._indent] = n;
    }.bind(this));
};

/* 显示选项-选择[**]时 
 * @param {Number} _params[0] 选项索引 
 * @param {String} _params[1] 选项文本 
 */
// When [**]
Game_Interpreter.prototype.command402 = function() {
    if (this._branch[this._indent] !== this._params[0]) {
        this.skipBranch();
    }
    return true;
};

/* 显示选项-当取消时 */
// When Cancel
Game_Interpreter.prototype.command403 = function() {
    if (this._branch[this._indent] &gt;= 0) {
        this.skipBranch();
    }
    return true;
};

/* 数值输入处理 
 * @param {Number} _params[0] 变量 ID 
 * @param {Number} _params[1] 位数 
 */
// Input Number
Game_Interpreter.prototype.command103 = function() {
    if (!$gameMessage.isBusy()) {
        this.setupNumInput(this._params);
        this._index;
        this.setWaitMode('message');
    }
    return false;
};

/* 设置数值输入 */
Game_Interpreter.prototype.setupNumInput = function(params) {
    $gameMessage.setNumberInput(params[0], params[1]);
};

/* 物品选择处理 
 * @param {Number} _params[0] 变量 ID 
 * @param {Number} _params[1] 物品类型（1：普通物品，2：重要物品，3：隐藏物品 A，4：隐藏物品 B） 
 */
// Select Item
Game_Interpreter.prototype.command104 = function() {
    if (!$gameMessage.isBusy()) {
        this.setupItemChoice(this._params);
        this._index;
        this.setWaitMode('message');
    }
    return false;
};

/* 设置物品选项 */
Game_Interpreter.prototype.setupItemChoice = function(params) {
    $gameMessage.setItemChoice(params[0], params[1] || 2);
};

/* 显示滚动文字 
 * @param {Number} _params[0] 速度 
 * @param {Boolean} _params[1] 是否禁止快进 
 */
// Show Scrolling Text
Game_Interpreter.prototype.command105 = function() {
    if (!$gameMessage.isBusy()) {
        $gameMessage.setScroll(this._params[0], this._params[1]);
        while (this.nextEventCode() === 405) {
            this._index;
            $gameMessage.add(this.currentCommand().parameters[0]);
        }
        this._index;
        this.setWaitMode('message');
    }
    return false;
};

/* 注释 
 * @param {String} _params[0] 注释文本 
 */
// Comment
Game_Interpreter.prototype.command108 = function() {
    this._comments = [this._params[0]];
    while (this.nextEventCode() === 408) {
        this._index;
        this._comments.push(this.currentCommand().parameters[0]);
    }
    return true;
};

/* 分支条件 
 * @param {Number} _params[0] 条件类型 
 * @param {Any} _params[1] 参数（不同条件不一样） 
 * @param {Any} _params[2] 参数（不同条件不一样） 
 */
// Conditional Branch
Game_Interpreter.prototype.command111 = function() {
    var result = false;
    switch (this._params[0]) {
        case 0:  // 开关（Switch） 
            result = ($gameSwitches.value(this._params[1]) === (this._params[2] === 0));
            break;
        case 1:  // 变量（Variable） 
            var value1 = $gameVariables.value(this._params[1]);
            var value2;
            if (this._params[2] === 0) {
                value2 = this._params[3];
            } else {
                value2 = $gameVariables.value(this._params[3]);
            }
            switch (this._params[4]) {
                case 0:  // 等于（Equal to） 
                    result = (value1 === value2);
                    break;
                case 1:  // 大于或等于（Greater than or Equal to） 
                    result = (value1 &gt;= value2);
                    break;
                case 2:  // 小于或等于（Less than or Equal to） 
                    result = (value1 &lt;= value2);
                    break;
                case 3:  // 大于（Greater than） 
                    result = (value1 &gt; value2);
                    break;
                case 4:  // 小于（Less than） 
                    result = (value1 &lt; value2);
                    break;
                case 5:  // 不等于（Not Equal to） 
                    result = (value1 !== value2);
                    break;
            }
            break;
        case 2:  // 独立开关（Self Switch） 
            if (this._eventId &gt; 0) {
                var key = [this._mapId, this._eventId, this._params[1]];
                result = ($gameSelfSwitches.value(key) === (this._params[2] === 0));
            }
            break;
        case 3:  // 计时器（Timer） 
            if ($gameTimer.isWorking()) {
                if (this._params[2] === 0) {
                    result = ($gameTimer.seconds() &gt;= this._params[1]);
                } else {
                    result = ($gameTimer.seconds() &lt;= this._params[1]);
                }
            }
            break;
        case 4:  // 角色（Actor） 
            var actor = $gameActors.actor(this._params[1]);
            if (actor) {
                var n = this._params[3];
                switch (this._params[2]) {
                    case 0:  // 在队伍中（In the Party） 
                        result = $gameParty.members().contains(actor);
                        break;
                    case 1:  // 名字（Name） 
                        result = (actor.name() === n);
                        break;
                    case 2:  // 职业（Class） 
                        result = actor.isClass($dataClasses[n]);
                        break;
                    case 3:  // 技能（Skill） 
                        result = actor.hasSkill(n);
                        break;
                    case 4:  // 武器（Weapon） 
                        result = actor.hasWeapon($dataWeapons[n]);
                        break;
                    case 5:  // 护甲（Armor） 
                        result = actor.hasArmor($dataArmors[n]);
                        break;
                    case 6:  // 状态（State） 
                        result = actor.isStateAffected(n);
                        break;
                }
            }
            break;
        case 5:  // 敌人（Enemy） 
            var enemy = $gameTroop.members()[this._params[1]];
            if (enemy) {
                switch (this._params[2]) {
                    case 0:  // 出现（Appeared） 
                        result = enemy.isAlive();
                        break;
                    case 1:  // 状态（State） 
                        result = enemy.isStateAffected(this._params[3]);
                        break;
                }
            }
            break;
        case 6:  // 人物（Character） 
            var character = this.character(this._params[1]);
            if (character) {
                result = (character.direction() === this._params[2]);
            }
            break;
        case 7:  // 金钱（Gold） 
            switch (this._params[2]) {
                case 0:  // 大于或等于（Greater than or equal to） 
                    result = ($gameParty.gold() &gt;= this._params[1]);
                    break;
                case 1:  // 小于或等于（Less than or equal to） 
                    result = ($gameParty.gold() &lt;= this._params[1]);
                    break;
                case 2:  // 小于（Less than） 
                    result = ($gameParty.gold() &lt; this._params[1]);
                    break;
            }
            break;
        case 8:  // 物品（Item） 
            result = $gameParty.hasItem($dataItems[this._params[1]]);
            break;
        case 9:  // 武器（Weapon） 
            result = $gameParty.hasItem($dataWeapons[this._params[1]], this._params[2]);
            break;
        case 10:  // 护甲（Armor） 
            result = $gameParty.hasItem($dataArmors[this._params[1]], this._params[2]);
            break;
        case 11:  // 按键（Button） 
            result = Input.isPressed(this._params[1]);
            break;
        case 12:  // 脚本（Script） 
            result = !!eval(this._params[1]);
            break;
        case 13:  // 载具（Vehicle） 
            result = ($gamePlayer.vehicle() === $gameMap.vehicle(this._params[1]));
            break;
    }
    this._branch[this._indent] = result;
    if (this._branch[this._indent] === false) {
        this.skipBranch();
    }
    return true;
};

/* 否则 */
// Else
Game_Interpreter.prototype.command411 = function() {
    if (this._branch[this._indent] !== false) {
        this.skipBranch();
    }
    return true;
};

/* 循环 */
// Loop
Game_Interpreter.prototype.command112 = function() {
    return true;
};

/* 重复以上内容 */
// Repeat Above
Game_Interpreter.prototype.command413 = function() {
    do {
        this._index--;
    } while (this.currentCommand().indent !== this._indent);
    return true;
};

/* 跳出循环 */
// Break Loop
Game_Interpreter.prototype.command113 = function() {
    var depth = 0;
    while (this._index &lt; this._list.length - 1) {
        this._index;
        var command = this.currentCommand();

        if (command.code === 112)
            depth;

        if (command.code === 413) {
            if (depth &gt; 0)
                depth--;
            else
                break;
        }
    }
    return true;
};

/* 中止事件处理 */
// Exit Event Processing
Game_Interpreter.prototype.command115 = function() {
    this._index = this._list.length;
    return true;
};

/* 公共事件 
 * @param {Number} _params[0] 公共事件 ID  
 */
// Common Event
Game_Interpreter.prototype.command117 = function() {
    var commonEvent = $dataCommonEvents[this._params[0]];
    if (commonEvent) {
        var eventId = this.isOnCurrentMap() ? this._eventId : 0;
        this.setupChild(commonEvent.list, eventId);
    }
    return true;
};

/* 设置子对象 */
Game_Interpreter.prototype.setupChild = function(list, eventId) {
    this._childInterpreter = new Game_Interpreter(this._depth + 1);
    this._childInterpreter.setup(list, eventId);
};

/* 标签 */
// Label
Game_Interpreter.prototype.command118 = function() {
    return true;
};

/* 转到标签 
 * @param {String} _params[0] 标签名称 
 */
// Jump to Label
Game_Interpreter.prototype.command119 = function() {
    var labelName = this._params[0];
    for (var i = 0; i &lt; this._list.length; i) {
        var command = this._list[i];
        if (command.code === 118 &amp;&amp; command.parameters[0] === labelName) {
            this.jumpTo(i);
            return;
        }
    }
    return true;
};

/* 跳转到该索引 */
Game_Interpreter.prototype.jumpTo = function(index) {
    var lastIndex = this._index;
    var startIndex = Math.min(index, lastIndex);
    var endIndex = Math.max(index, lastIndex);
    var indent = this._indent;
    for (var i = startIndex; i &lt;= endIndex; i) {
        var newIndent = this._list[i].indent;
        if (newIndent !== indent) {
            this._branch[indent] = null;
            indent = newIndent;
        }
    }
    this._index = index;
};

/* 开关操作 
 * @param {Number} _params[0] 起始开关 ID 
 * @param {Number} _params[1] 结尾开关 ID 
 * @param {Number} _params[2] 操作（0：ON，1：OFF） 
 */
// Control Switches
Game_Interpreter.prototype.command121 = function() {
    for (var i = this._params[0]; i &lt;= this._params[1]; i) {
        $gameSwitches.setValue(i, this._params[2] === 0);
    }
    return true;
};

/* 变量操作 
 * @param {Number} _params[0] 起始变量 ID 
 * @param {Number} _params[1] 结尾变量 ID 
 * @param {Number} _params[2] 操作（0：代入，1：加法，2：减法，3：乘法，4：除法，5：取模） 
 * @param {Number} _params[3] 操作数（0：常量，1：变量，2：随机，3：游戏数据，4：脚本） 
 * @param {Any} _params[4] 参数（不同操作数不一样） 
 * @param {Any} _params[5] 参数（不同操作数不一样） 
 * @param {Any} _params[6] 参数（不同操作数不一样） 
 */
// Control Variables
Game_Interpreter.prototype.command122 = function() {
    var value = 0;
    switch (this._params[3]) { // 操作符（Operand） 
        case 0: // 常量（Constant） 
            value = this._params[4];
            break;
        case 1: // 变量（Variable） 
            value = $gameVariables.value(this._params[4]);
            break;
        case 2: // 随机数（Random） 
            value = this._params[5] - this._params[4] + 1;
            for (var i = this._params[0]; i &lt;= this._params[1]; i) {
                this.operateVariable(i, this._params[2], this._params[4] + Math.randomInt(value));
            }
            return true;
            break;
        case 3: // 游戏数据（Game Data） 
            value = this.gameDataOperand(this._params[4], this._params[5], this._params[6]);
            break;
        case 4: // 脚本（Script） 
            value = eval(this._params[4]);
            break;
    }
    for (var i = this._params[0]; i &lt;= this._params[1]; i) {
        this.operateVariable(i, this._params[2], value);
    }
    return true;
};

/* 游戏数据操作 */
Game_Interpreter.prototype.gameDataOperand = function(type, param1, param2) {
    switch (type) {
    case 0:  // 物品（Item） 
        return $gameParty.numItems($dataItems[param1]);
    case 1:  // 武器（Weapon） 
        return $gameParty.numItems($dataWeapons[param1]);
    case 2:  // 护甲（Armor） 
        return $gameParty.numItems($dataArmors[param1]);
    case 3:  // 角色（Actor） 
        var actor = $gameActors.actor(param1);
        if (actor) {
            switch (param2) {
            case 0:  // 等级（Level） 
                return actor.level;
            case 1:  // 经验值（EXP） 
                return actor.currentExp();
            case 2:  // HP
                return actor.hp;
            case 3:  // MP
                return actor.mp;
            default:    // 能力值（Parameter） 
                if (param2 &gt;= 4 &amp;&amp; param2 &lt;= 11) {
                    return actor.param(param2 - 4);
                }
            }
        }
        break;
    case 4:  // 敌人（Enemy） 
        var enemy = $gameTroop.members()[param1];
        if (enemy) {
            switch (param2) {
            case 0:  // HP
                return enemy.hp;
            case 1:  // MP
                return enemy.mp;
            default:    // 能力值（Parameter） 
                if (param2 &gt;= 2 &amp;&amp; param2 &lt;= 9) {
                    return enemy.param(param2 - 2);
                }
            }
        }
        break;
    case 5:  // 人物（Character） 
        var character = this.character(param1);
        if (character) {
            switch (param2) {
            case 0:  // 地图 X（Map X） 
                return character.x;
            case 1:  // 地图 Y（Map Y） 
                return character.y;
            case 2:  // 方向（Direction） 
                return character.direction();
            case 3:  // 画面 X（Screen X） 
                return character.screenX();
            case 4:  // 画面 Y（Screen Y） 
                return character.screenY();
            }
        }
        break;
    case 6:  // 队伍（Party） 
        actor = $gameParty.members()[param1];
        return actor ? actor.actorId() : 0;
    case 7:  // 其他（Other） 
        switch (param1) {
        case 0:  // 地图 ID（Map ID） 
            return $gameMap.mapId();
        case 1:  // 队伍成员（Party Members） 
            return $gameParty.size();
        case 2:  // 金钱（Gold） 
            return $gameParty.gold();
        case 3:  // 步数（Steps） 
            return $gameParty.steps();
        case 4:  // 游戏时间（Play Time） 
            return $gameSystem.playtime();
        case 5:  // 计时器（Timer） 
            return $gameTimer.seconds();
        case 6:  // 保存次数（Save Count） 
            return $gameSystem.saveCount();
        case 7:  // 战斗次数（Battle Count） 
            return $gameSystem.battleCount();
        case 8:  // 胜利次数（Win Count） 
            return $gameSystem.winCount();
        case 9:  // 逃跑次数（Escape Count） 
            return $gameSystem.escapeCount();
        }
        break;
    }
    return 0;
};

/* 操作变量 */
Game_Interpreter.prototype.operateVariable = function(variableId, operationType, value) {
    try {
        var oldValue = $gameVariables.value(variableId);
        switch (operationType) {
        case 0:  // 代入（Set） 
            $gameVariables.setValue(variableId, oldValue = value);
            break;
        case 1:  // 加法（Add） 
            $gameVariables.setValue(variableId, oldValue + value);
            break;
        case 2:  // 减法（Sub） 
            $gameVariables.setValue(variableId, oldValue - value);
            break;
        case 3:  // 乘法（Mul） 
            $gameVariables.setValue(variableId, oldValue * value);
            break;
        case 4:  // 除法（Div） 
            $gameVariables.setValue(variableId, oldValue / value);
            break;
        case 5:  // 取模（Mod） 
            $gameVariables.setValue(variableId, oldValue % value);
            break;
        }
    } catch (e) {
        $gameVariables.setValue(variableId, 0);
    }
};

/* 独立开关操作 
 * @param {String} _params[0] 独立开关（A：独立开关 A，B：独立开关 B，C：独立开关 C，D：独立开关 D） 
 * @param {Number} _params[1] 操作（0：ON，1：OFF） 
 */
// Control Self Switch
Game_Interpreter.prototype.command123 = function() {
    if (this._eventId &gt; 0) {
        var key = [this._mapId, this._eventId, this._params[0]];
        $gameSelfSwitches.setValue(key, this._params[1] === 0);
    }
    return true;
};

/* 计时器操作 
 * @param {Number} _params[0] 操作（0：开始，1：停止） 
 * @param {Number} _params[1] 时间（单位秒） 
 */
// Control Timer
Game_Interpreter.prototype.command124 = function() {
    if (this._params[0] === 0) {  // 开始（Start） 
        $gameTimer.start(this._params[1] * 60);
    } else {  // 停止（Stop） 
        $gameTimer.stop();
    }
    return true;
};

/* 增减金钱 
 * @param {Number} _params[0] 操作（0：增加，1：减少） 
 * @param {Number} _params[1] 操作数类型（0：常量，1：变量） 
 * @param {Number} _params[2] 操作数 
 */
// Change Gold
Game_Interpreter.prototype.command125 = function() {
    var value = this.operateValue(this._params[0], this._params[1], this._params[2]);
    $gameParty.gainGold(value);
    return true;
};

/* 增减物品 
 * @param {Number} _params[0] 物品 ID 
 * @param {Number} _params[1] 操作（0：增加，1：减少） 
 * @param {Number} _params[2] 操作数类型（0：常量，1：变量） 
 * @param {Number} _params[3] 操作数 
 */
// Change Items
Game_Interpreter.prototype.command126 = function() {
    var value = this.operateValue(this._params[1], this._params[2], this._params[3]);
    $gameParty.gainItem($dataItems[this._params[0]], value);
    return true;
};

/* 增减武器 
 * @param {Number} _params[0] 武器 ID 
 * @param {Number} _params[1] 操作（0：增加，1：减少） 
 * @param {Number} _params[2] 操作数类型（0：常量，1：变量） 
 * @param {Number} _params[3] 操作数 
 * @param {Boolean} _params[4] 是否包括装备 
 */
// Change Weapons
Game_Interpreter.prototype.command127 = function() {
    var value = this.operateValue(this._params[1], this._params[2], this._params[3]);
    $gameParty.gainItem($dataWeapons[this._params[0]], value, this._params[4]);
    return true;
};

/* 增减护甲
 * @param {Number} _params[0] 护甲 ID 
 * @param {Number} _params[1] 操作（0：增加，1：减少） 
 * @param {Number} _params[2] 操作数类型（0：常量，1：变量） 
 * @param {Number} _params[3] 操作数 
 * @param {Boolean} _params[4] 是否包括装备 
 */
// Change Armors
Game_Interpreter.prototype.command128 = function() {
    var value = this.operateValue(this._params[1], this._params[2], this._params[3]);
    $gameParty.gainItem($dataArmors[this._params[0]], value, this._params[4]);
    return true;
};

/* 队伍管理 
 * @param {Number} _params[0] 角色 ID 
 * @param {Number} _params[1] 操作（0：入队，1：离队） 
 * @param {Boolean} _params[2] 是否初始化 
 */
// Change Party Member
Game_Interpreter.prototype.command129 = function() {
    var actor = $gameActors.actor(this._params[0]);
    if (actor) {
        if (this._params[1] === 0) {  // 入队（Add） 
            if (this._params[2]) {   // 初始化（Initialize） 
                $gameActors.actor(this._params[0]).setup(this._params[0]);
            }
            $gameParty.addActor(this._params[0]);
        } else {  // 离队（Remove） 
            $gameParty.removeActor(this._params[0]);
        }
    }
    return true;
};

/* 更改战斗 BGM 
 * @param {String} _params[0].name 名称 
 * @param {Number} _params[0].volume 音量 
 * @param {Number} _params[0].pitch 音调 
 * @param {Number} _params[0].pan 声像 
 */
// Change Battle BGM
Game_Interpreter.prototype.command132 = function() {
    $gameSystem.setBattleBgm(this._params[0]);
    return true;
};

/* 更改胜利 ME 
 * @param {String} _params[0].name 名称 
 * @param {Number} _params[0].volume 音量 
 * @param {Number} _params[0].pitch 音调 
 * @param {Number} _params[0].pan 声像 
 */
// Change Victory ME
Game_Interpreter.prototype.command133 = function() {
    $gameSystem.setVictoryMe(this._params[0]);
    return true;
};

/* 启动/禁用存档
 * @param {Number} _params[0] 存档（0：禁用，1：启用） 
 */
// Change Save Access
Game_Interpreter.prototype.command134 = function() {
    if (this._params[0] === 0) {
        $gameSystem.disableSave();
    } else {
        $gameSystem.enableSave();
    }
    return true;
};

/* 启动/禁用菜单 
 * @param {Number} _params[0] 菜单（0：禁用，1：启用） 
 */
// Change Menu Access
Game_Interpreter.prototype.command135 = function() {
    if (this._params[0] === 0) {
        $gameSystem.disableMenu();
    } else {
        $gameSystem.enableMenu();
    }
    return true;
};

/* 启动/禁用遇敌 
 * @param {Number} _params[0] 遇敌（0：禁用，1：启用） 
 */
// Change Encounter Disable
Game_Interpreter.prototype.command136 = function() {
    if (this._params[0] === 0) {
        $gameSystem.disableEncounter();
    } else {
        $gameSystem.enableEncounter();
    }
    $gamePlayer.makeEncounterCount();
    return true;
};

/* 启动/禁用整队
 * @param {Number} _params[0] 整队（0：禁用，1：启用） 
 */
// Change Formation Access
Game_Interpreter.prototype.command137 = function() {
    if (this._params[0] === 0) {
        $gameSystem.disableFormation();
    } else {
        $gameSystem.enableFormation();
    }
    return true;
};

/* 更改窗口颜色
 * @param {Number} _params[0][0] 红 
 * @param {Number} _params[0][1] 绿 
 * @param {Number} _params[0][2] 蓝 
 * @param {Number} _params[0][3] 不透明度 
 */
// Change Window Color
Game_Interpreter.prototype.command138 = function() {
    $gameSystem.setWindowTone(this._params[0]);
    return true;
};

/* 更改战败 ME 
 * @param {String} _params[0].name 名称 
 * @param {Number} _params[0].volume 音量 
 * @param {Number} _params[0].pitch 音调 
 * @param {Number} _params[0].pan 声像 
 */
// Change Defeat ME
Game_Interpreter.prototype.command139 = function() {
    $gameSystem.setDefeatMe(this._params[0]);
    return true;
};

/* 更改载具 BGM 
 * @param {Number} _params[0] 载具（0：小舟，1：大船，2：飞艇） 
 * @param {String} _params[1].name 名称 
 * @param {Number} _params[1].volume 音量 
 * @param {Number} _params[1].pitch 音调 
 * @param {Number} _params[1].pan 声像 
 */
// Change Vehicle BGM
Game_Interpreter.prototype.command140 = function() {
    var vehicle = $gameMap.vehicle(this._params[0]);
    if (vehicle) {
        vehicle.setBgm(this._params[1]);
    }
    return true;
};

/* 场所移动 
 * @param {Number} _params[0] 指定方式（0：直接指定，1：变量指定） 
 * @param {Number} _params[1] 地图 ID【直接指定】，或地图 ID 的变量 ID【变量指定】 
 * @param {Number} _params[2] 坐标 X【直接指定】，或坐标 X 的变量 ID【变量指定】 
 * @param {Number} _params[3] 坐标 Y【直接指定】，或坐标 Y 的变量 ID【变量指定】 
 * @param {Number} _params[4] 方向（0：不变，2：下，4：左，6：右，8：上） 
 * @param {Number} _params[5] 淡入淡出（0：黑，1：白，无：2） 
 */
// Transfer Player
Game_Interpreter.prototype.command201 = function() {
    if (!$gameParty.inBattle() &amp;&amp; !$gameMessage.isBusy()) {
        var mapId, x, y;
        if (this._params[0] === 0) {  // 直接指定（Direct designation） 
            mapId = this._params[1];
            x = this._params[2];
            y = this._params[3];
        } else {  // 变量指定（Designation with variables） 
            mapId = $gameVariables.value(this._params[1]);
            x = $gameVariables.value(this._params[2]);
            y = $gameVariables.value(this._params[3]);
        }
        $gamePlayer.reserveTransfer(mapId, x, y, this._params[4], this._params[5]);
        this.setWaitMode('transfer');
        this._index;
    }
    return false;
};

/* 设置载具位置 
 * @param {Number} _params[0] 载具（0：小舟，1：大船，2：飞艇） 
 * @param {Number} _params[1] 指定方式（0：直接指定，1：变量指定） 
 * @param {Number} _params[2] 地图 ID【直接指定】，或地图 ID 的变量 ID【变量指定】 
 * @param {Number} _params[3] 坐标 X【直接指定】，或坐标 X 的变量 ID【变量指定】 
 * @param {Number} _params[4] 坐标 Y【直接指定】，或坐标 Y 的变量 ID【变量指定】 
 */
// Set Vehicle Location
Game_Interpreter.prototype.command202 = function() {
    var mapId, x, y;
    if (this._params[1] === 0) {  // 直接指定（Direct designation） 
        mapId = this._params[2];
        x = this._params[3];
        y = this._params[4];
    } else {  // 变量指定（Designation with variables） 
        mapId = $gameVariables.value(this._params[2]);
        x = $gameVariables.value(this._params[3]);
        y = $gameVariables.value(this._params[4]);
    }
    var vehicle = $gameMap.vehicle(this._params[0]);
    if (vehicle) {
        vehicle.setLocation(mapId, x, y);
    }
    return true;
};

/* 设置事件位置 
 * @param {Number} _params[0] 人物（0：本事件，大于 0：其他事件）
 * @param {Number} _params[1] 指定方式（0：直接指定，1：变量指定，2：与其他事件交换） 
 * @param {Number} _params[2] 坐标 X【直接指定】，或坐标 X 的变量 ID【变量指定】，或事件 ID（0：本事件，大于 0：其他事件）【与其他事件交换】 
 * @param {Number} _params[3] 坐标 Y【直接指定】，或坐标 Y 的变量 ID【变量指定】
 * @param {Number} _params[4] 方向（0：不变，2：下，4：左，6：右，8：上） 
 */
// Set Event Location
Game_Interpreter.prototype.command203 = function() {
    var character = this.character(this._params[0]);
    if (character) {
        if (this._params[1] === 0) {  // 直接指定（Direct designation） 
            character.locate(this._params[2], this._params[3]);
        } else if (this._params[1] === 1) {  //变量指定（Designation with variables） 
            var x = $gameVariables.value(this._params[2]);
            var y = $gameVariables.value(this._params[3]);
            character.locate(x, y);
        } else {  // 与其他事件交换（Exchange with another event） 
            var character2 = this.character(this._params[2]);
            if (character2) {
                character.swap(character2);
            }
        }
        if (this._params[4] &gt; 0) {
            character.setDirection(this._params[4]);
        }
    }
    return true;
};

/* 滚动地图 
 * @param {Number} _params[0] 方向（2：下，4：左，6：右，8：上） 
 * @param {Number} _params[1] 距离 
 * @param {Number} _params[2] 速度（1：1/8 倍速，2：1/4 倍速，3：1/2 倍速，4：标准速度，5：2 倍速，6：4 倍速） 
 */
// Scroll Map
Game_Interpreter.prototype.command204 = function() {
    if (!$gameParty.inBattle()) {
        if ($gameMap.isScrolling()) {
            this.setWaitMode('scroll');
            return false;
        }
        $gameMap.startScroll(this._params[0], this._params[1], this._params[2]);
    }
    return true;
};

/* 设置移动路线 
 * @param {Number} _params[0] 人物（小于 0：玩家，0：本事件，大于 0：其他事件） 
 * @param {Array} _params[1].list 移动路线 
 * @param {Boolean} _params[1].repeat 是否循环执行 
 * @param {Boolean} _params[1].skippable 是否无法移动时跳过指令 
 * @param {Boolean} _params[1].wait 是否等待完成 
 */
// Set Movement Route
Game_Interpreter.prototype.command205 = function() {
    $gameMap.refreshIfNeeded();
    this._character = this.character(this._params[0]);
    if (this._character) {
        this._character.forceMoveRoute(this._params[1]);
        if (this._params[1].wait) {
            this.setWaitMode('route');
        }
    }
    return true;
};

/* 载具乘降 */
// Getting On and Off Vehicles
Game_Interpreter.prototype.command206 = function() {
    $gamePlayer.getOnOffVehicle();
    return true;
};

/* 更改透明状态 
 * @param {Number} _params[0] 透明状态（0：ON，1：OFF） 
 */
// Change Transparency
Game_Interpreter.prototype.command211 = function() {
    $gamePlayer.setTransparent(this._params[0] === 0);
    return true;
};

/* 显示动画 
 * @param {Number} _params[0] 人物（小于 0：玩家，0：本事件，大于 0：其他事件） 
 * @param {Number} _params[1] 动画 ID 
 * @param {Boolean} _params[2] 是否等待完成 
 */
// Show Animation
Game_Interpreter.prototype.command212 = function() {
    this._character = this.character(this._params[0]);
    if (this._character) {
        this._character.requestAnimation(this._params[1]);
        if (this._params[2]) {
            this.setWaitMode('animation');
        }
    }
    return true;
};

/* 显示气泡图标
 * @param {Number} _params[0] 人物（小于 0：玩家，0：本事件，大于 0：其他事件） 
 * @param {Number} _params[1] 气泡图标 ID 
 * @param {Boolean} _params[2] 是否等待完成 
 */
// Show Balloon Icon
Game_Interpreter.prototype.command213 = function() {
    this._character = this.character(this._params[0]);
    if (this._character) {
        this._character.requestBalloon(this._params[1]);
        if (this._params[2]) {
            this.setWaitMode('balloon');
        }
    }
    return true;
};

/* 暂时消除事件 */
// Erase Event
Game_Interpreter.prototype.command214 = function() {
    if (this.isOnCurrentMap() &amp;&amp; this._eventId &gt; 0) {
        $gameMap.eraseEvent(this._eventId);
    }
    return true;
};

/* 更改队列行进 
 * @param {Number} _params[0] 队列步行（0：ON，1：OFF） 
 */
// Change Player Followers
Game_Interpreter.prototype.command216 = function() {
    if (this._params[0] === 0) {
        $gamePlayer.showFollowers();
    } else {
        $gamePlayer.hideFollowers();
    }
    $gamePlayer.refresh();
    return true;
};

/* 集合队列成员 */
// Gather Followers
Game_Interpreter.prototype.command217 = function() {
    if (!$gameParty.inBattle()) {
        $gamePlayer.gatherFollowers();
        this.setWaitMode('gather');
    }
    return true;
};

/* 淡出画面 */
// Fadeout Screen
Game_Interpreter.prototype.command221 = function() {
    if (!$gameMessage.isBusy()) {
        $gameScreen.startFadeOut(this.fadeSpeed());
        this.wait(this.fadeSpeed());
        this._index;
    }
    return false;
};

/* 淡入画面 */
// Fadein Screen
Game_Interpreter.prototype.command222 = function() {
    if (!$gameMessage.isBusy()) {
        $gameScreen.startFadeIn(this.fadeSpeed());
        this.wait(this.fadeSpeed());
        this._index;
    }
    return false;
};

/* 更改画面色调 
 * @param {Number} _params[0][0] 红 
 * @param {Number} _params[0][1] 绿 
 * @param {Number} _params[0][2] 蓝 
 * @param {Number} _params[0][3] 灰度 
 * @param {Number} _params[1] 持续时间（单位帧） 
 * @param {Boolean} _params[2] 是否等待完成 
 */
// Tint Screen
Game_Interpreter.prototype.command223 = function() {
    $gameScreen.startTint(this._params[0], this._params[1]);
    if (this._params[2]) {
        this.wait(this._params[1]);
    }
    return true;
};

/* 闪烁画面 
 * @param {Number} _params[0][0] 红 
 * @param {Number} _params[0][1] 绿 
 * @param {Number} _params[0][2] 蓝 
 * @param {Number} _params[0][3] 强度 
 * @param {Number} _params[1] 持续时间（单位帧） 
 * @param {Boolean} _params[2] 是否等待完成 
*/
// Flash Screen
Game_Interpreter.prototype.command224 = function() {
    $gameScreen.startFlash(this._params[0], this._params[1]);
    if (this._params[2]) {
        this.wait(this._params[1]);
    }
    return true;
};

/* 震动屏幕 
 * @param {Number} _params[0][0] 强度 
 * @param {Number} _params[0][1] 速度 
 * @param {Number} _params[1] 持续时间（单位帧） 
 * @param {Boolean} _params[2] 是否等待完成 
 */
// Shake Screen
Game_Interpreter.prototype.command225 = function() {
    $gameScreen.startShake(this._params[0], this._params[1], this._params[2]);
    if (this._params[3]) {
        this.wait(this._params[2]);
    }
    return true;
};

/* 等待 
 * @param {Number} _params[0] 持续时间（单位帧） 
 */
// Wait
Game_Interpreter.prototype.command230 = function() {
    this.wait(this._params[0]);
    return true;
};

/* 显示图片
 * @param {Number} _params[0] 编号 
 * @param {String} _params[1] 图像名称 
 * @param {Number} _params[2] 原点（0：左上，1：中心） 
 * @param {Number} _params[3] 指定方式（0：直接指定，1：变量指定） 
 * @param {Number} _params[4] 坐标 X【直接指定】，或坐标 X 的变量 ID【变量指定】 
 * @param {Number} _params[5] 坐标 Y【直接指定】，或坐标 Y 的变量 ID【变量指定】 
 * @param {Number} _params[6] 宽缩放率（百分比） 
 * @param {Number} _params[7] 高缩放率（百分比） 
 * @param {Number} _params[8] 不透明度 
 * @param {Number} _params[9] 合成方式（0：正常，1：叠加，2：正片叠底，3：滤色） 
 */
// Show Picture
Game_Interpreter.prototype.command231 = function() {
    var x, y;
    if (this._params[3] === 0) {  // 直接指定（Direct designation） 
        x = this._params[4];
        y = this._params[5];
    } else {  // 变量指定（Designation with variables） 
        x = $gameVariables.value(this._params[4]);
        y = $gameVariables.value(this._params[5]);
    }
    $gameScreen.showPicture(this._params[0], this._params[1], this._params[2],
        x, y, this._params[6], this._params[7], this._params[8], this._params[9]);
    return true;
};

/* 移动图片 
 * @param {Number} _params[0] 编号 
 * @param {Number} _params[1] 0 
 * @param {Number} _params[2] 原点（0：左上，1：中心） 
 * @param {Number} _params[3] 指定方式（0：直接指定，1：变量指定） 
 * @param {Number} _params[4] 坐标 X【直接指定】，或坐标 X 的变量 ID【变量指定】 
 * @param {Number} _params[5] 坐标 Y【直接指定】，或坐标 Y 的变量 ID【变量指定】 
 * @param {Number} _params[6] 宽缩放率（百分比） 
 * @param {Number} _params[7] 高缩放率（百分比） 
 * @param {Number} _params[8] 不透明度 
 * @param {Number} _params[9] 合成方式（0：正常，1：叠加，2：正片叠底，3：滤色） 
 * @param {Number} _params[10] 持续时间（单位帧） 
 * @param {Boolean} _params[11] 是否等待完成 
*/
// Move Picture
Game_Interpreter.prototype.command232 = function() {
    var x, y;
    if (this._params[3] === 0) {  // 直接指定（Direct designation） 
        x = this._params[4];
        y = this._params[5];
    } else {  // 变量指定（Designation with variables） 
        x = $gameVariables.value(this._params[4]);
        y = $gameVariables.value(this._params[5]);
    }
    $gameScreen.movePicture(this._params[0], this._params[2], x, y, this._params[6],
        this._params[7], this._params[8], this._params[9], this._params[10]);
    if (this._params[11]) {
        this.wait(this._params[10]);
    }
    return true;
};

/* 旋转图片 
 * @param {Number} _params[0] 编号 
 * @param {Number} _params[1] 速度 
 */
// Rotate Picture
Game_Interpreter.prototype.command233 = function() {
    $gameScreen.rotatePicture(this._params[0], this._params[1]);
    return true;
};

/* 更改图片色调 
 * @param {Number} _params[0] 编号 
 * @param {Number} _params[1][0] 红 
 * @param {Number} _params[1][1] 绿 
 * @param {Number} _params[1][2] 蓝 
 * @param {Number} _params[1][3] 灰度 
 * @param {Number} _params[2] 持续时间（单位帧） 
 * @param {Boolean} _params[3] 是否等待完成 
 */
// Tint Picture
Game_Interpreter.prototype.command234 = function() {
    $gameScreen.tintPicture(this._params[0], this._params[1], this._params[2]);
    if (this._params[3]) {
        this.wait(this._params[2]);
    }
    return true;
};

/* 消除图片 
 * @param {Number} _params[0] 编号 
 */
// Erase Picture
Game_Interpreter.prototype.command235 = function() {
    $gameScreen.erasePicture(this._params[0]);
    return true;
};

/* 设置天气 
 * @param {String} _params[0] 类型（none：无，rain：雨，storm：风暴，snow：雪） 
 * @param {Number} _params[1] 强度 
 * @param {Number} _params[2] 持续时间（单位帧） 
 * @param {Boolean} _params[3] 是否等待完成 
 */
// Set Weather Effect
Game_Interpreter.prototype.command236 = function() {
    if (!$gameParty.inBattle()) {
        $gameScreen.changeWeather(this._params[0], this._params[1], this._params[2]);
        if (this._params[3]) {
            this.wait(this._params[2]);
        }
    }
    return true;
};

/* 播放 BGM 
 * @param {String} _params[0].name 名称 
 * @param {Number} _params[0].volume 音量 
 * @param {Number} _params[0].pitch 音调 
 * @param {Number} _params[0].pan 声像 
 */
// Play BGM
Game_Interpreter.prototype.command241 = function() {
    AudioManager.playBgm(this._params[0]);
    return true;
};

/* 淡出 BGM 
 * @param {Number} _params[0] 持续时间（单位秒） 
 */
// Fadeout BGM
Game_Interpreter.prototype.command242 = function() {
    AudioManager.fadeOutBgm(this._params[0]);
    return true;
};

/* 保存 BGM */
// Save BGM
Game_Interpreter.prototype.command243 = function() {
    $gameSystem.saveBgm();
    return true;
};

/* 还原 BGM */
// Resume BGM
Game_Interpreter.prototype.command244 = function() {
    $gameSystem.replayBgm();
    return true;
};

/* 播放 BGS 
 * @param {String} _params[0].name 名称 
 * @param {Number} _params[0].volume 音量 
 * @param {Number} _params[0].pitch 音调 
 * @param {Number} _params[0].pan 声像 
 */
// Play BGS
Game_Interpreter.prototype.command245 = function() {
    AudioManager.playBgs(this._params[0]);
    return true;
};

/* 淡出 BGS 
 * @param {Number} _params[0] 持续时间（单位秒） 
 */
// Fadeout BGS
Game_Interpreter.prototype.command246 = function() {
    AudioManager.fadeOutBgs(this._params[0]);
    return true;
};

/* 播放 ME 
 * @param {String} _params[0].name 名称 
 * @param {Number} _params[0].volume 音量 
 * @param {Number} _params[0].pitch 音调 
 * @param {Number} _params[0].pan 声像 
 */
// Play ME
Game_Interpreter.prototype.command249 = function() {
    AudioManager.playMe(this._params[0]);
    return true;
};

/* 播放 SE 
 * @param {String} _params[0].name 名称 
 * @param {Number} _params[0].volume 音量 
 * @param {Number} _params[0].pitch 音调 
 * @param {Number} _params[0].pan 声像 
 */
// Play SE
Game_Interpreter.prototype.command250 = function() {
    AudioManager.playSe(this._params[0]);
    return true;
};

/* 停止 SE */
// Stop SE
Game_Interpreter.prototype.command251 = function() {
    AudioManager.stopSe();
    return true;
};

/* 播放影像 
 * @param {String} _params[0] 影像名称 
 */
// Play Movie
Game_Interpreter.prototype.command261 = function() {
    if (!$gameMessage.isBusy()) {
        var name = this._params[0];
        if (name.length &gt; 0) {
            var ext = this.videoFileExt();
            Graphics.playVideo('movies/' + name + ext);
            this.setWaitMode('video');
        }
        this._index;
    }
    return false;
};

/* 影像文件扩展名 */
Game_Interpreter.prototype.videoFileExt = function() {
    if (Graphics.canPlayVideoType('video/webm') &amp;&amp; !Utils.isMobileDevice()) {
        return '.webm';
    } else {
        return '.mp4';
    }
};

/* 启动/禁用显示地图名称 
 * @param {Number} _params[0] 显示地图名称（0：ON，1：OFF） 
 */
// Change Map Name Display
Game_Interpreter.prototype.command281 = function() {
    if (this._params[0] === 0) {
        $gameMap.enableNameDisplay();
    } else {
        $gameMap.disableNameDisplay();
    }
    return true;
};

/* 更改地图图块 
 * @param {Number} _params[0] 图块 ID 
 */
// Change Tileset
Game_Interpreter.prototype.command282 = function() {
    var tileset = $dataTilesets[this._params[0]];
    if(!this._imageReservationId){
        this._imageReservationId = Utils.generateRuntimeId();
    }

    var allReady = tileset.tilesetNames.map(function(tilesetName) {
        return ImageManager.reserveTileset(tilesetName, 0, this._imageReservationId);
    }, this).every(function(bitmap) {return bitmap.isReady();});

    if (allReady) {
        $gameMap.changeTileset(this._params[0]);
        ImageManager.releaseReservation(this._imageReservationId);
        this._imageReservationId = null;

        return true;
    } else {
        return false;
    }
};

/* 更改战斗背景 
 * @param {String} _params[0] 图像 1 名称 
 * @param {String} _params[1] 图像 2 名称 
 */
// Change Battle Back
Game_Interpreter.prototype.command283 = function() {
    $gameMap.changeBattleback(this._params[0], this._params[1]);
    return true;
};

/* 更改远景 
 * @param {String} _params[0] 图像名称 
 * @param {Boolean} _params[1] 是否横向循环 
 * @param {Boolean} _params[2] 是否纵向循环 
 * @param {Number} _params[3] 横向滚动速度 
 * @param {Number} _params[4] 纵向滚动速度 
 */
// Change Parallax
Game_Interpreter.prototype.command284 = function() {
    $gameMap.changeParallax(this._params[0], this._params[1],
        this._params[2], this._params[3], this._params[4]);
    return true;
};

/* 获取指定位置的信息 
 * @param {Number} _params[0] 变量 ID 
 * @param {Number} _params[1] 信息类型（0：地形标志，1：事件 ID，2：图块 ID（第 1 层），3：图块 ID（第 2 层）4：图块 ID（第 3 层）5：图块 ID（第 4 层），6：区域 ID） 
 * @param {Number} _params[2] 指定方式（0：直接指定，1：变量指定） 
 * @param {Number} _params[3] 坐标 X【直接指定】，或坐标 X 的变量 ID【变量指定】 
 * @param {Number} _params[4] 坐标 Y【直接指定】，或坐标 Y 的变量 ID【变量指定】 
 */
// Get Location Info
Game_Interpreter.prototype.command285 = function() {
    var x, y, value;
    if (this._params[2] === 0) {  // 直接指定（Direct designation） 
        x = this._params[3];
        y = this._params[4];
    } else {  // 变量指定（Designation with variables） 
        x = $gameVariables.value(this._params[3]);
        y = $gameVariables.value(this._params[4]);
    }
    switch (this._params[1]) {
    case 0:     // 地形标志（Terrain Tag） 
        value = $gameMap.terrainTag(x, y);
        break;
    case 1:     // 事件 ID（Event ID） 
        value = $gameMap.eventIdXy(x, y);
        break;
    case 2:     // 图块 ID（第 1 层）（Tile ID (Layer 1)） 
    case 3:     // 图块 ID（第 2 层）（Tile ID (Layer 2)） 
    case 4:     // 图块 ID（第 3 层）（Tile ID (Layer 3)） 
    case 5:     // 图块 ID（第 4 层）（Tile ID (Layer 4)） 
        value = $gameMap.tileId(x, y, this._params[1] - 2);
        break;
    default:    // 区域 ID （Region ID） 
        value = $gameMap.regionId(x, y);
        break;
    }
    $gameVariables.setValue(this._params[0], value);
    return true;
};

/* 战斗处理 
 * @param {Number} _params[0] 指定方式（0：直接指定，1：变量指定，3：与随机遇敌相同） 
 * @param {Number} _params[1] 敌群 ID【直接指定】，或敌群 ID 的变量 ID【变量指定】 
 * @param {Boolean} _params[2] 是否允许逃跑 
 * @param {Boolean} _params[3] 是否允许失败 
 */
// Battle Processing
Game_Interpreter.prototype.command301 = function() {
    if (!$gameParty.inBattle()) {
        var troopId;
        if (this._params[0] === 0) {  // 直接指定（Direct designation） 
            troopId = this._params[1];
        } else if (this._params[0] === 1) {  // 变量指定（Designation with variables） 
            troopId = $gameVariables.value(this._params[1]);
        } else {  // 与随机遇敌相同（Same as Random Encounter） 
            troopId = $gamePlayer.makeEncounterTroopId();
        }
        if ($dataTroops[troopId]) {
            BattleManager.setup(troopId, this._params[2], this._params[3]);
            BattleManager.setEventCallback(function(n) {
                this._branch[this._indent] = n;
            }.bind(this));
            $gamePlayer.makeEncounterCount();
            SceneManager.push(Scene_Battle);
        }
    }
    return true;
};

/* 战斗处理-胜利时（允许战败或逃跑时） */
// If Win
Game_Interpreter.prototype.command601 = function() {
    if (this._branch[this._indent] !== 0) {
        this.skipBranch();
    }
    return true;
};

/* 战斗处理-逃跑时（允许逃跑时） */
// If Escape
Game_Interpreter.prototype.command602 = function() {
    if (this._branch[this._indent] !== 1) {
        this.skipBranch();
    }
    return true;
};

/* 战斗处理-战败时（允许战败时） */
// If Lose
Game_Interpreter.prototype.command603 = function() {
    if (this._branch[this._indent] !== 2) {
        this.skipBranch();
    }
    return true;
};

/* 商店处理 
 * @param {Number} _params[0] 商品类型（0：物品，1：武器，2：护甲） 
 * @param {Number} _params[1] 物品 ID 
 * @param {Number} _params[2] 价格方式（0：标准，1：指定） 
 * @param {Number} _params[3] 价格 
 * @param {Number} _params[4] 是否只能购买 
 */
// Shop Processing
Game_Interpreter.prototype.command302 = function() {
    if (!$gameParty.inBattle()) {
        var goods = [this._params];
        while (this.nextEventCode() === 605) {
            this._index;
            goods.push(this.currentCommand().parameters);
        }
        SceneManager.push(Scene_Shop);
        SceneManager.prepareNextScene(goods, this._params[4]);
    }
    return true;
};

/* 名字输入处理 
 * @param {Number} _params[0] 角色 ID 
 * @param {Number} _params[1] 最大字符数 
 */
// Name Input Processing
Game_Interpreter.prototype.command303 = function() {
    if (!$gameParty.inBattle()) {
        if ($dataActors[this._params[0]]) {
            SceneManager.push(Scene_Name);
            SceneManager.prepareNextScene(this._params[0], this._params[1]);
        }
    }
    return true;
};

/* 增减 HP 
 * @param {Number} _params[0] 角色指定方式（0：固定，1：变量） 
 * @param {Number} _params[1] 角色 ID（0 为全体队友）【固定】,或角色 ID 的变量 ID【变量】 
 * @param {Number} _params[2] 操作（0：增加，1：减少） 
 * @param {Number} _params[3] 操作数类型（0：常量，1：变量） 
 * @param {Number} _params[4] 操作数 
 * @param {Boolean} _params[5] 是否允许导致无法战斗 
 */
// Change HP
Game_Interpreter.prototype.command311 = function() {
    var value = this.operateValue(this._params[2], this._params[3], this._params[4]);
    this.iterateActorEx(this._params[0], this._params[1], function(actor) {
        this.changeHp(actor, value, this._params[5]);
    }.bind(this));
    return true;
};

/* 增减 MP 
 * @param {Number} _params[0] 角色指定方式（0：固定，1：变量） 
 * @param {Number} _params[1] 角色 ID（0 为全体队友）【固定】,或角色 ID 的变量 ID【变量】 
 * @param {Number} _params[2] 操作（0：增加，1：减少） 
 * @param {Number} _params[3] 操作数类型（0：常量，1：变量） 
 * @param {Number} _params[4] 操作数 
 */
// Change MP
Game_Interpreter.prototype.command312 = function() {
    var value = this.operateValue(this._params[2], this._params[3], this._params[4]);
    this.iterateActorEx(this._params[0], this._params[1], function(actor) {
        actor.gainMp(value);
    }.bind(this));
    return true;
};

/* 增减 TP
 * @param {Number} _params[0] 角色指定方式（0：固定，1：变量） 
 * @param {Number} _params[1] 角色 ID（0 为全体队友）【固定】，或角色 ID 的变量 ID【变量】 
 * @param {Number} _params[2] 操作（0：增加，1：减少） 
 * @param {Number} _params[3] 操作数类型（0：常量，1：变量） 
 * @param {Number} _params[4] 操作数 
 */
// Change TP
Game_Interpreter.prototype.command326 = function() {
    var value = this.operateValue(this._params[2], this._params[3], this._params[4]);
    this.iterateActorEx(this._params[0], this._params[1], function(actor) {
        actor.gainTp(value);
    }.bind(this));
    return true;
};

/* 更改状态
 * @param {Number} _params[0] 角色指定方式（0：固定，1：变量） 
 * @param {Number} _params[1] 角色 ID（0 为全体队友）【固定】，或角色 ID 的变量 ID【变量】 
 * @param {Number} _params[2] 操作（0：附加，1：解除） 
 * @param {Number} _params[3] 状态 ID 
 */
// Change State
Game_Interpreter.prototype.command313 = function() {
    this.iterateActorEx(this._params[0], this._params[1], function(actor) {
        var alreadyDead = actor.isDead();
        if (this._params[2] === 0) {
            actor.addState(this._params[3]);
        } else {
            actor.removeState(this._params[3]);
        }
        if (actor.isDead() &amp;&amp; !alreadyDead) {
            actor.performCollapse();
        }
        actor.clearResult();
    }.bind(this));
    return true;
};

/* 完全恢复 
 * @param {Number} _params[0] 角色指定方式（0：固定，1：变量） 
 * @param {Number} _params[1] 角色 ID（0 为全体队友）【固定】，或角色 ID 的变量 ID【变量】 
 */
// Recover All
Game_Interpreter.prototype.command314 = function() {
    this.iterateActorEx(this._params[0], this._params[1], function(actor) {
        actor.recoverAll();
    }.bind(this));
    return true;
};

/* 增减经验值 
 * @param {Number} _params[0] 角色指定方式（0：固定，1：变量） 
 * @param {Number} _params[1] 角色 ID（0 为全体队友）【固定】，或角色 ID 的变量 ID【变量】 
 * @param {Number} _params[2] 操作（0：增加，1：减少） 
 * @param {Number} _params[3] 操作数类型（0：常量，1：变量） 
 * @param {Number} _params[4] 操作数 
 * @param {Boolean} _params[5] 是否显示升级信息 
 */
// Change EXP
Game_Interpreter.prototype.command315 = function() {
    var value = this.operateValue(this._params[2], this._params[3], this._params[4]);
    this.iterateActorEx(this._params[0], this._params[1], function(actor) {
        actor.changeExp(actor.currentExp() + value, this._params[5]);
    }.bind(this));
    return true;
};

/* 增减等级 
 * @param {Number} _params[0] 角色指定方式（0：固定，1：变量） 
 * @param {Number} _params[1] 角色 ID（0 为全体队友）【固定】，或角色 ID 的变量 ID【变量】 
 * @param {Number} _params[2] 操作（0：增加，1：减少） 
 * @param {Number} _params[3] 操作数类型（0：常量，1：变量） 
 * @param {Number} _params[4] 操作数 
 * @param {Boolean} _params[5] 是否显示升级信息 
 */
// Change Level
Game_Interpreter.prototype.command316 = function() {
    var value = this.operateValue(this._params[2], this._params[3], this._params[4]);
    this.iterateActorEx(this._params[0], this._params[1], function(actor) {
        actor.changeLevel(actor.level + value, this._params[5]);
    }.bind(this));
    return true;
};

/* 增减能力值 
 * @param {Number} _params[0] 角色指定方式（0：固定，1：变量） 
 * @param {Number} _params[1] 角色 ID（0 为全体队友）【固定】，或角色 ID 的变量 ID【变量】 
 * @param {Number} _params[2] 能力值 ID
 * @param {Number} _params[3] 操作（0：增加，1：减少） 
 * @param {Number} _params[4] 操作数类型（0：常量，1：变量） 
 * @param {Number} _params[5] 操作数
 */
// Change Parameter
Game_Interpreter.prototype.command317 = function() {
    var value = this.operateValue(this._params[3], this._params[4], this._params[5]);
    this.iterateActorEx(this._params[0], this._params[1], function(actor) {
        actor.addParam(this._params[2], value);
    }.bind(this));
    return true;
};

/* 增减技能 
 * @param {Number} _params[0] 角色指定方式（0：固定，1：变量） 
 * @param {Number} _params[1] 角色 ID（0 为全体队友）【固定】，或角色 ID 的变量 ID【变量】 
 * @param {Number} _params[2] 操作（0：学习，1：遗忘） 
 * @param {Number} _params[3] 技能 ID 
 */
// Change Skill
Game_Interpreter.prototype.command318 = function() {
    this.iterateActorEx(this._params[0], this._params[1], function(actor) {
        if (this._params[2] === 0) {
            actor.learnSkill(this._params[3]);
        } else {
            actor.forgetSkill(this._params[3]);
        }
    }.bind(this));
    return true;
};

/* 更改装备 
 * @param {Number} _params[0] 角色 ID 
 * @param {Number} _params[1] 装备类型 ID 
 * @param {Number} _params[2] 装备物品 ID 
 */
// Change Equipment
Game_Interpreter.prototype.command319 = function() {
    var actor = $gameActors.actor(this._params[0]);
    if (actor) {
        actor.changeEquipById(this._params[1], this._params[2]);
    }
    return true;
};

/* 更改名字
 * @param {Number} _params[0] 角色 ID 
 * @param {String} _params[1] 名字 
 */
// Change Name
Game_Interpreter.prototype.command320 = function() {
    var actor = $gameActors.actor(this._params[0]);
    if (actor) {
        actor.setName(this._params[1]);
    }
    return true;
};

/* 更改职业 
 * @param {Number} _params[0] 角色 ID 
 * @param {Number} _params[1] 职业 ID 
 * @param {Boolean} _params[2] 是否保存等级 
 */
// Change Class
Game_Interpreter.prototype.command321 = function() {
    var actor = $gameActors.actor(this._params[0]);
    if (actor &amp;&amp; $dataClasses[this._params[1]]) {
        actor.changeClass(this._params[1], this._params[2]);
    }
    return true;
};

/* 更改角色图像 
 * @param {Number} _params[0] 角色 ID 
 * @param {String} _params[1] 行走图名称 
 * @param {Number} _params[2] 行走图索引 
 * @param {String} _params[3] 脸图名称 
 * @param {Number} _params[4] 脸图索引 
 * @param {String} _params[5] 战斗图名称 
 */
// Change Actor Images
Game_Interpreter.prototype.command322 = function() {
    var actor = $gameActors.actor(this._params[0]);
    if (actor) {
        actor.setCharacterImage(this._params[1], this._params[2]);
        actor.setFaceImage(this._params[3], this._params[4]);
        actor.setBattlerImage(this._params[5]);
    }
    $gamePlayer.refresh();
    return true;
};

/* 更改载具图像 
 * @param {Number} _params[0] 载具（0：小舟，1：大船，2：飞艇） 
 * @param {String} _params[1] 图像名称 
 */
// Change Vehicle Image
Game_Interpreter.prototype.command323 = function() {
    var vehicle = $gameMap.vehicle(this._params[0]);
    if (vehicle) {
        vehicle.setImage(this._params[1], this._params[2]);
    }
    return true;
};

/* 更改昵称
 * @param {Number} _params[0] 角色 ID 
 * @param {String} _params[1] 昵称 
 */
// Change Nickname
Game_Interpreter.prototype.command324 = function() {
    var actor = $gameActors.actor(this._params[0]);
    if (actor) {
        actor.setNickname(this._params[1]);
    }
    return true;
};

/* 更改简介 
 * @param {Number} _params[0] 角色 ID 
 * @param {String} _params[1] 简介 
 */
// Change Profile
Game_Interpreter.prototype.command325 = function() {
    var actor = $gameActors.actor(this._params[0]);
    if (actor) {
        actor.setProfile(this._params[1]);
    }
    return true;
};

/* 增减敌人 HP 
 * @param {Number} _params[0] 敌人索引（-1 为敌方全体） 
 * @param {Number} _params[1] 操作（0：增加，1：减少） 
 * @param {Number} _params[2] 操作数类型（0：常量，1：变量） 
 * @param {Number} _params[3] 操作数 
 * @param {Boolean} _params[4] 是否允许导致无法战斗 
 */
// Change Enemy HP
Game_Interpreter.prototype.command331 = function() {
    var value = this.operateValue(this._params[1], this._params[2], this._params[3]);
    this.iterateEnemyIndex(this._params[0], function(enemy) {
        this.changeHp(enemy, value, this._params[4]);
    }.bind(this));
    return true;
};

/* 增减敌人 MP 
 * @param {Number} _params[0] 敌人索引（-1 为敌方全体） 
 * @param {Number} _params[1] 操作（0：增加，1：减少） 
 * @param {Number} _params[2] 操作数类型（0：常量，1：变量） 
 * @param {Number} _params[3] 操作数 
 */
// Change Enemy MP
Game_Interpreter.prototype.command332 = function() {
    var value = this.operateValue(this._params[1], this._params[2], this._params[3]);
    this.iterateEnemyIndex(this._params[0], function(enemy) {
        enemy.gainMp(value);
    }.bind(this));
    return true;
};

/* 增减敌人 TP 
 * @param {Number} _params[0] 敌人索引（-1 为敌方全体） 
 * @param {Number} _params[1] 操作（0：增加，1：减少） 
 * @param {Number} _params[2] 操作数类型（0：常量，1：变量） 
 * @param {Number} _params[3] 操作数 
 */
// Change Enemy TP
Game_Interpreter.prototype.command342 = function() {
    var value = this.operateValue(this._params[1], this._params[2], this._params[3]);
    this.iterateEnemyIndex(this._params[0], function(enemy) {
        enemy.gainTp(value);
    }.bind(this));
    return true;
};

/* 更改敌人状态 
 * @param {Number} _params[0] 敌人索引（-1 为敌方全体） 
 * @param {Number} _params[1] 操作（0：附加，1：解除） 
 * @param {Number} _params[2] 状态 ID 
 */
// Change Enemy State
Game_Interpreter.prototype.command333 = function() {
    this.iterateEnemyIndex(this._params[0], function(enemy) {
        var alreadyDead = enemy.isDead();
        if (this._params[1] === 0) {
            enemy.addState(this._params[2]);
        } else {
            enemy.removeState(this._params[2]);
        }
        if (enemy.isDead() &amp;&amp; !alreadyDead) {
            enemy.performCollapse();
        }
        enemy.clearResult();
    }.bind(this));
    return true;
};

/* 敌人完全恢复 
 * @param {Number} _params[0] 敌人索引（-1 为敌方全体） 
 */
// Enemy Recover All
Game_Interpreter.prototype.command334 = function() {
    this.iterateEnemyIndex(this._params[0], function(enemy) {
        enemy.recoverAll();
    }.bind(this));
    return true;
};

/* 敌人出现 
 * @param {Number} _params[0] 敌人索引 
 */
// Enemy Appear
Game_Interpreter.prototype.command335 = function() {
    this.iterateEnemyIndex(this._params[0], function(enemy) {
        enemy.appear();
        $gameTroop.makeUniqueNames();
    }.bind(this));
    return true;
};

/* 敌人变身 
 * @param {Number} _params[0] 敌人索引 
 * @param {Number} _params[0] 敌群 ID 
 */
// Enemy Transform
Game_Interpreter.prototype.command336 = function() {
    this.iterateEnemyIndex(this._params[0], function(enemy) {
        enemy.transform(this._params[1]);
        $gameTroop.makeUniqueNames();
    }.bind(this));
    return true;
};

/* 显示战斗动画 
 * @param {Number} _params[0] 敌人索引 
 * @param {Number} _params[1] 动画 ID 
 * @param {Boolean} _params[2] 是否以敌方全体为目标 
 */
// Show Battle Animation
Game_Interpreter.prototype.command337 = function() {
    if (this._params[2] == true) {
        this.iterateEnemyIndex(-1,function(enemy) {
            if (enemy.isAlive()) {
                enemy.startAnimation(this._params[1],false,0);
            }
        }.bind(this));
    } else {
        this.iterateEnemyIndex(this._params[0], function (enemy) {
            if (enemy.isAlive()) {
                enemy.startAnimation(this._params[1], false, 0);
            }
        }.bind(this));
    }
    return true;
};

/* 强制战斗行动 
 * @param {Number} _params[0] 行动主体类型（0：敌人，1：角色） 
 * @param {Number} _params[1] 敌人索引【敌人】，或角色 ID【角色】 
 * @param {Number} _params[2] 技能 ID 
 * @param {Number} _params[3] 目标（-2：上一个目标，-1：随机，0：索引 1，1：索引 2，2：索引 3，3：索引 4，4：索引 5，5：索引 6，6：索引 7，7：索引 8） 
 */
// Force Action
Game_Interpreter.prototype.command339 = function() {
    this.iterateBattler(this._params[0], this._params[1], function(battler) {
        if (!battler.isDeathStateAffected()) {
            battler.forceAction(this._params[2], this._params[3]);
            BattleManager.forceAction(battler);
            this.setWaitMode('action');
        }
    }.bind(this));
    return true;
};

/* 中断战斗 */
// Abort Battle
Game_Interpreter.prototype.command340 = function() {
    BattleManager.abort();
    return true;
};

/* 打开菜单画面 */
// Open Menu Screen
Game_Interpreter.prototype.command351 = function() {
    if (!$gameParty.inBattle()) {
        SceneManager.push(Scene_Menu);
        Window_MenuCommand.initCommandPosition();
    }
    return true;
};

/* 打开存档画面 */
// Open Save Screen
Game_Interpreter.prototype.command352 = function() {
    if (!$gameParty.inBattle()) {
        SceneManager.push(Scene_Save);
    }
    return true;
};

/* 游戏结束 */
// Game Over
Game_Interpreter.prototype.command353 = function() {
    SceneManager.goto(Scene_Gameover);
    return true;
};

/* 返回标题画面 */
// Return to Title Screen
Game_Interpreter.prototype.command354 = function() {
    SceneManager.goto(Scene_Title);
    return true;
};

/* 脚本 */
// Script
Game_Interpreter.prototype.command355 = function() {
    var script = this.currentCommand().parameters[0] + '\n';
    while (this.nextEventCode() === 655) {
        this._index;
        script += this.currentCommand().parameters[0] + '\n';
    }
    eval(script);
    return true;
};

/* 插件指令 
 * @param {String} _params[0] 插件指令 
 */
// Plugin Command
Game_Interpreter.prototype.command356 = function() {
    var args = this._params[0].split(" ");
    var command = args.shift();
    this.pluginCommand(command, args);
    return true;
};

/* 插件指令 
 * 插件通过重写该方法来实现插件指令的功能。
 */
Game_Interpreter.prototype.pluginCommand = function(command, args) {
    // 被插件重写 
    // to be overridden by plugins
};

/* 请求图像 */
Game_Interpreter.requestImages = function(list, commonList){
    if(!list) return;

    list.forEach(function(command){
        var params = command.parameters;
        switch(command.code){
            // 显示文字（Show Text）
            case 101:
                ImageManager.requestFace(params[0]);
                break;

            // 公共事件（Common Event）
            case 117:
                var commonEvent = $dataCommonEvents[params[0]];
                if (commonEvent) {
                    if (!commonList) {
                        commonList = [];
                    }
                    if (!commonList.contains(params[0])) {
                        commonList.push(params[0]);
                        Game_Interpreter.requestImages(commonEvent.list, commonList);
                    }
                }
                break;

            // 队伍管理（Change Party Member）
            case 129:
                var actor = $gameActors.actor(params[0]);
                if (actor &amp;&amp; params[1] === 0) {
                    var name = actor.characterName();
                    ImageManager.requestCharacter(name);
                }
                break;

            // 设置移动路线（Set Movement Route）
            case 205:
                if(params[1]){
                    params[1].list.forEach(function(command){
                        var params = command.parameters;
                        if(command.code === Game_Character.ROUTE_CHANGE_IMAGE){
                            ImageManager.requestCharacter(params[0]);
                        }
                    });
                }
                break;

            // 显示动画，显示战斗动画（Show Animation, Show Battle Animation）
            case 212: case 337:
                if(params[1]) {
                    var animation = $dataAnimations[params[1]];
                    var name1 = animation.animation1Name;
                    var name2 = animation.animation2Name;
                    var hue1 = animation.animation1Hue;
                    var hue2 = animation.animation2Hue;
                    ImageManager.requestAnimation(name1, hue1);
                    ImageManager.requestAnimation(name2, hue2);
                }
                break;

            // 更改队列行进（Change Player Followers）
            case 216:
                if (params[0] === 0) {
                    $gamePlayer.followers().forEach(function(follower) {
                        var name = follower.characterName();
                        ImageManager.requestCharacter(name);
                    });
                }
                break;

            // 显示图片（Show Picture）
            case 231:
                ImageManager.requestPicture(params[1]);
                break;

            // 更改地图图块（Change Tileset）
            case 282:
                var tileset = $dataTilesets[params[0]];
                tileset.tilesetNames.forEach(function(tilesetName){
                    ImageManager.requestTileset(tilesetName);
                });
                break;

            // 更改战斗背景（Change Battle Back）
            case 283:
                if ($gameParty.inBattle()) {
                    ImageManager.requestBattleback1(params[0]);
                    ImageManager.requestBattleback2(params[1]);
                }
                break;

            // 更改远景（Change Parallax）
            case 284:
                if (!$gameParty.inBattle()) {
                    ImageManager.requestParallax(params[0]);
                }
                break;

            // 更改角色图像（Change Actor Images）
            case 322:
                ImageManager.requestCharacter(params[1]);
                ImageManager.requestFace(params[3]);
                ImageManager.requestSvActor(params[5]);
                break;

            // 更改载具图像（Change Vehicle Image）
            case 323:
                var vehicle = $gameMap.vehicle(params[0]);
                if(vehicle){
                    ImageManager.requestCharacter(params[1]);
                }
                break;

            // 敌人变身（Enemy Transform）
            case 336:
                var enemy = $dataEnemies[params[1]];
                var name = enemy.battlerName;
                var hue = enemy.battlerHue;
                if ($gameSystem.isSideView()) {
                    ImageManager.requestSvEnemy(name, hue);
                } else {
                    ImageManager.requestEnemy(name, hue);
                }
                break;
        }
    });
};</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_场景_rpg_scenes_js">场景: rpg_scenes.js</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Scene_Base: 游戏中所有场景的父类</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Scene_Boot: 场景_启动</p>
</li>
<li>
<p>Scene_Title: 场景_标题</p>
</li>
<li>
<p>Scene_Map: 场景_地图</p>
</li>
<li>
<p>Scene_MenuBase: 场景_菜单父类</p>
<div class="olist loweralpha">
<ol class="loweralpha" type="a">
<li>
<p>Scene_Menu: 场景_菜单</p>
</li>
<li>
<p>Scene_ItemBase: 场景_项目父类</p>
<div class="olist lowerroman">
<ol class="lowerroman" type="i">
<li>
<p>Scene_Item: 场景_物品</p>
</li>
<li>
<p>Scene_Skill: 场景_技能</p>
</li>
</ol>
</div>
</li>
<li>
<p>Scene_Equip: 场景_装备</p>
</li>
<li>
<p>Scene_Status: 场景_状态</p>
</li>
<li>
<p>Scene_Options: 场景_设置</p>
</li>
<li>
<p>Scene_File: 场景_存档文件</p>
<div class="olist lowerroman">
<ol class="lowerroman" type="i">
<li>
<p>Scene_Save: 场景_存档</p>
</li>
<li>
<p>Scene_Load: 场景_读档.</p>
</li>
</ol>
</div>
</li>
<li>
<p>Scene_GameEnd: 场景_游戏结束</p>
</li>
<li>
<p>Scene_Shop: 场景_商店</p>
</li>
<li>
<p>Scene_Name: 场景_名字</p>
</li>
<li>
<p>Scene_Debug: 场景_调试</p>
</li>
</ol>
</div>
</li>
<li>
<p>Scene_Battle: 场景_战斗</p>
</li>
<li>
<p>Scene_Gameover: 场景_游戏结束</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-javascript" data-lang="javascript">//=============================================================================
// rpg_scenes.js v1.6.1
//=============================================================================

//=============================================================================

/**
 * 游戏中所有场景的父类。 
 * The Superclass of all scene within the game.
 * 
 * @class Scene_Base
 * @constructor 
 * @extends Stage
 */
function Scene_Base() {
    this.initialize.apply(this, arguments);
}

Scene_Base.prototype = Object.create(Stage.prototype);
Scene_Base.prototype.constructor = Scene_Base;


/**
 * 创建一个 Scene_Base 的实例。 
 * Create a instance of Scene_Base.
 * 
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.initialize = function() {
    Stage.prototype.initialize.call(this);
    this._active = false;
    this._fadeSign = 0;
    this._fadeDuration = 0;
    this._fadeSprite = null;
    this._imageReservationId = Utils.generateRuntimeId();
};

/**
 * 附加一个预留到预留队列。 
 * Attach a reservation to the reserve queue.
 * 
 * @method attachReservation
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.attachReservation = function() {
    ImageManager.setDefaultReservationId(this._imageReservationId);
};

/**
 * 从预留队列移除一个预留。 
 * Remove the reservation from the Reserve queue.
 * 
 * @method detachReservation
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.detachReservation = function() {
    ImageManager.releaseReservation(this._imageReservationId);
};

/**
 * 创建组件并将其添加到渲染流程中。 
 * Create the components and add them to the rendering process.
 * 
 * @method create
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.create = function() {
};

/**
 * 返回场景是否处于活动状态。 
 * Returns whether the scene is active or not.
 * 
 * @method isActive
 * @instance 
 * @memberof Scene_Base
 * @return {Boolean} return true if the scene is active
 */
Scene_Base.prototype.isActive = function() {
    return this._active;
};

/**
 * 返回场景是否准备好开始。 
 * Return whether the scene is ready to start or not.
 * 
 * @method isReady
 * @instance 
 * @memberof Scene_Base
 * @return {Boolean} 如果场景准备好开始则返回 true（Return true if the scene is ready to start）
 */
Scene_Base.prototype.isReady = function() {
    return ImageManager.isReady();
};

/**
 * 开始场景流程。 
 * Start the scene processing.
 * 
 * @method start
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.start = function() {
    this._active = true;
};

/**
 * 每个新帧更新场景流程。 
 * Update the scene processing each new frame.
 * 
 * @method update
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.update = function() {
    this.updateFade();
    this.updateChildren();
};

/**
 * 停止场景流程。 
 * Stop the scene processing.
 * 
 * @method stop
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.stop = function() {
    this._active = false;
};


/**
 * 返回场景是否繁忙。 
 * Return whether the scene is busy or not.
 * 
 * @method isBusy
 * @instance
 * @memberof Scene_Base
 * @return {Boolean} 如果场景当前正繁忙则返回 true（Return true if the scene is currently busy）
 */
Scene_Base.prototype.isBusy = function() {
    return this._fadeDuration &gt; 0;
};

/**
 * 在切换到另一个场景之前结束场景。 
 * Terminate the scene before switching to a another scene.
 * 
 * @method terminate
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.terminate = function() {
};

/**
 * 创建子窗口图层并将其添加到渲染流程里。 
 * Create the layer for the windows children
 * and add it to the rendering process.
 * 
 * @method createWindowLayer
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.createWindowLayer = function() {
    var width = Graphics.boxWidth;
    var height = Graphics.boxHeight;
    var x = (Graphics.width - width) / 2;
    var y = (Graphics.height - height) / 2;
    this._windowLayer = new WindowLayer();
    this._windowLayer.move(x, y, width, height);
    this.addChild(this._windowLayer);
};

/**
 * 将子窗口添加到 WindowLayer 流程。 
 * Add the children window to the windowLayer processing.
 * 
 * @method addWindow
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.addWindow = function(window) {
    this._windowLayer.addChild(window);
};

/**
 * 请求淡入画面流程。 
 * Request a fadeIn screen process.
 * 
 * @method startFadeIn
 * @param {Number} [duration=30] 在画面上进行淡入处理所需的时间（TThe time the process will take for fadeIn the screen） 
 * @param {Boolean} [white=false] 如果为真，淡入将用白色处理，否则将是黑色（If true the fadein will be process with a white color else it's will be black）
 * 
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.startFadeIn = function(duration, white) {
    this.createFadeSprite(white);
    this._fadeSign = 1;
    this._fadeDuration = duration || 30;
    this._fadeSprite.opacity = 255;
};

/**
 * 请求淡出画面流程。 
 * Request a fadeOut screen process.
 * 
 * @method startFadeOut
 * @param {Number} [duration=30] 在画面上进行淡出处理所需的时间（The time the process will take for fadeOut the screen）
 * @param {Boolean} [white=false] 如果为真，淡出将用白色处理，否则将是黑色（If true the fadeOut will be process with a white color else it's will be black）
 * 
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.startFadeOut = function(duration, white) {
    this.createFadeSprite(white);
    this._fadeSign = -1;
    this._fadeDuration = duration || 30;
    this._fadeSprite.opacity = 0;
};

/**
 * 为淡入和淡出创建一个画面精灵，并将其添加到渲染流程中。 
 * Create a Screen sprite for the fadein and fadeOut purpose and
 * add it to the rendering process.
 * 
 * @method createFadeSprite
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.createFadeSprite = function(white) {
    if (!this._fadeSprite) {
        this._fadeSprite = new ScreenSprite();
        this.addChild(this._fadeSprite);
    }
    if (white) {
        this._fadeSprite.setWhite();
    } else {
        this._fadeSprite.setBlack();
    }
};

/**
 * 更新画面渐变流程。 
 * Update the screen fade processing.
 * 
 * @method updateFade
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.updateFade = function() {
    if (this._fadeDuration &gt; 0) {
        var d = this._fadeDuration;
        if (this._fadeSign &gt; 0) {
            this._fadeSprite.opacity -= this._fadeSprite.opacity / d;
        } else {
            this._fadeSprite.opacity = (255 - this._fadeSprite.opacity) / d;
        }
        this._fadeDuration--;
    }
};

/**
 * 每帧更新场景的子元素。 
 * Update the children of the scene EACH frame.
 * 
 * @method updateChildren
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.updateChildren = function() {
    this.children.forEach(function(child) {
        if (child.update) {
            child.update();
        }
    });
};

/**
 * 从堆栈数组中弹出场景并切换到上一个场景。 
 * Pop the scene from the stack array and switch to the
 * previous scene.
 * 
 * @method popScene
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.popScene = function() {
    SceneManager.pop();
};

/**
 * 检查游戏是否应该触发游戏结束。 
 * Check whether the game should be triggering a gameover.
 * 
 * @method checkGameover
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.checkGameover = function() {
    if ($gameParty.isAllDead()) {
        SceneManager.goto(Scene_Gameover);
    }
};

/**
 * 缓慢地淡出场景的所有视觉和音频。 
 * Slowly fade out all the visual and audio of the scene.
 * 
 * @method fadeOutAll
 * @instance 
 * @memberof Scene_Base
 */
Scene_Base.prototype.fadeOutAll = function() {
    var time = this.slowFadeSpeed() / 60;
    AudioManager.fadeOutBgm(time);
    AudioManager.fadeOutBgs(time);
    AudioManager.fadeOutMe(time);
    this.startFadeOut(this.slowFadeSpeed());
};

/**
 * 返回画面渐变速度值。 
 * Return the screen fade speed value.
 * 
 * @method fadeSpeed
 * @instance 
 * @memberof Scene_Base
 * @return {Number} 返回渐变速度（Return the fade speed） 
 */
Scene_Base.prototype.fadeSpeed = function() {
    return 24;
};

/**
 * 返回一个缓慢的画面渐变速度值。 
 * Return a slow screen fade speed value.
 * 
 * @method slowFadeSpeed
 * @instance 
 * @memberof Scene_Base
 * @return {Number} 返回渐变速度（Return the fade speed） 
 */
Scene_Base.prototype.slowFadeSpeed = function() {
    return this.fadeSpeed() * 2;
};

//-----------------------------------------------------------------------------
// 场景_启动 
// Scene_Boot
// 
// 初始化整个游戏的场景类。 
// The scene class for initializing the entire game.

function Scene_Boot() {
    this.initialize.apply(this, arguments);
}

Scene_Boot.prototype = Object.create(Scene_Base.prototype);
Scene_Boot.prototype.constructor = Scene_Boot;

/* 初始化 */
Scene_Boot.prototype.initialize = function() {
    Scene_Base.prototype.initialize.call(this);
    this._startDate = Date.now();
};

/* 创建 */
Scene_Boot.prototype.create = function() {
    Scene_Base.prototype.create.call(this);
    DataManager.loadDatabase();
    ConfigManager.load();
    this.loadSystemWindowImage();
};

/* 加载系统窗口图像 */
Scene_Boot.prototype.loadSystemWindowImage = function() {
    ImageManager.reserveSystem('Window');
};

/* 加载系统图像 */
Scene_Boot.loadSystemImages = function() {
    ImageManager.reserveSystem('IconSet');
    ImageManager.reserveSystem('Balloon');
    ImageManager.reserveSystem('Shadow1');
    ImageManager.reserveSystem('Shadow2');
    ImageManager.reserveSystem('Damage');
    ImageManager.reserveSystem('States');
    ImageManager.reserveSystem('Weapons1');
    ImageManager.reserveSystem('Weapons2');
    ImageManager.reserveSystem('Weapons3');
    ImageManager.reserveSystem('ButtonSet');
};

/* 是否准备好 */
Scene_Boot.prototype.isReady = function() {
    if (Scene_Base.prototype.isReady.call(this)) {
        return DataManager.isDatabaseLoaded() &amp;&amp; this.isGameFontLoaded();
    } else {
        return false;
    }
};

/* 是否游戏字体加载了 */
Scene_Boot.prototype.isGameFontLoaded = function() {
    if (Graphics.isFontLoaded('GameFont')) {
        return true;
    } else if (!Graphics.canUseCssFontLoading()){
        var elapsed = Date.now() - this._startDate;
        if (elapsed &gt;= 60000) {
            throw new Error('Failed to load GameFont');
        }
    }
};

/* 开始 */
Scene_Boot.prototype.start = function() {
    Scene_Base.prototype.start.call(this);
    SoundManager.preloadImportantSounds();
    if (DataManager.isBattleTest()) {
        DataManager.setupBattleTest();
        SceneManager.goto(Scene_Battle);
    } else if (DataManager.isEventTest()) {
        DataManager.setupEventTest();
        SceneManager.goto(Scene_Map);
    } else {
        this.checkPlayerLocation();
        DataManager.setupNewGame();
        SceneManager.goto(Scene_Title);
        Window_TitleCommand.initCommandPosition();
    }
    this.updateDocumentTitle();
};

/* 更新文档标题 */
Scene_Boot.prototype.updateDocumentTitle = function() {
    document.title = $dataSystem.gameTitle;
};

/* 检测玩家位置 */
Scene_Boot.prototype.checkPlayerLocation = function() {
    if ($dataSystem.startMapId === 0) {
        throw new Error('Player\'s starting position is not set');
    }
};

//-----------------------------------------------------------------------------
// 场景_标题 
// Scene_Title
//
// 标题场景的场景类。 
// The scene class of the title screen.

function Scene_Title() {
    this.initialize.apply(this, arguments);
}

Scene_Title.prototype = Object.create(Scene_Base.prototype);
Scene_Title.prototype.constructor = Scene_Title;

/* 初始化 */
Scene_Title.prototype.initialize = function() {
    Scene_Base.prototype.initialize.call(this);
};

/* 创建 */
Scene_Title.prototype.create = function() {
    Scene_Base.prototype.create.call(this);
    this.createBackground();
    this.createForeground();
    this.createWindowLayer();
    this.createCommandWindow();
};

/* 开始 */
Scene_Title.prototype.start = function() {
    Scene_Base.prototype.start.call(this);
    SceneManager.clearStack();
    this.centerSprite(this._backSprite1);
    this.centerSprite(this._backSprite2);
    this.playTitleMusic();
    this.startFadeIn(this.fadeSpeed(), false);
};

/* 更新 */
Scene_Title.prototype.update = function() {
    if (!this.isBusy()) {
        this._commandWindow.open();
    }
    Scene_Base.prototype.update.call(this);
};

/* 是否繁忙 */
Scene_Title.prototype.isBusy = function() {
    return this._commandWindow.isClosing() || Scene_Base.prototype.isBusy.call(this);
};

/* 结束 */
Scene_Title.prototype.terminate = function() {
    Scene_Base.prototype.terminate.call(this);
    SceneManager.snapForBackground();
};

/* 创建背景 */
Scene_Title.prototype.createBackground = function() {
    this._backSprite1 = new Sprite(ImageManager.loadTitle1($dataSystem.title1Name));
    this._backSprite2 = new Sprite(ImageManager.loadTitle2($dataSystem.title2Name));
    this.addChild(this._backSprite1);
    this.addChild(this._backSprite2);
};

/* 创建前景 */
Scene_Title.prototype.createForeground = function() {
    this._gameTitleSprite = new Sprite(new Bitmap(Graphics.width, Graphics.height));
    this.addChild(this._gameTitleSprite);
    if ($dataSystem.optDrawTitle) {
        this.drawGameTitle();
    }
};

/* 绘制游戏标题 */
Scene_Title.prototype.drawGameTitle = function() {
    var x = 20;
    var y = Graphics.height / 4;
    var maxWidth = Graphics.width - x * 2;
    var text = $dataSystem.gameTitle;
    this._gameTitleSprite.bitmap.outlineColor = 'black';
    this._gameTitleSprite.bitmap.outlineWidth = 8;
    this._gameTitleSprite.bitmap.fontSize = 72;
    this._gameTitleSprite.bitmap.drawText(text, x, y, maxWidth, 48, 'center');
};

/* 中心精灵
 * 将精灵放置在画面中心。
 */
Scene_Title.prototype.centerSprite = function(sprite) {
    sprite.x = Graphics.width / 2;
    sprite.y = Graphics.height / 2;
    sprite.anchor.x = 0.5;
    sprite.anchor.y = 0.5;
};

/* 创建指令窗口 */
Scene_Title.prototype.createCommandWindow = function() {
    this._commandWindow = new Window_TitleCommand();
    this._commandWindow.setHandler('newGame',  this.commandNewGame.bind(this));
    this._commandWindow.setHandler('continue', this.commandContinue.bind(this));
    this._commandWindow.setHandler('options',  this.commandOptions.bind(this));
    this.addWindow(this._commandWindow);
};

/* 开始游戏的指令 */
Scene_Title.prototype.commandNewGame = function() {
    DataManager.setupNewGame();
    this._commandWindow.close();
    this.fadeOutAll();
    SceneManager.goto(Scene_Map);
};

/* 继续游戏的指令 */
Scene_Title.prototype.commandContinue = function() {
    this._commandWindow.close();
    SceneManager.push(Scene_Load);
};

/* 设置的指令 */
Scene_Title.prototype.commandOptions = function() {
    this._commandWindow.close();
    SceneManager.push(Scene_Options);
};

/* 播放标题音乐 */
Scene_Title.prototype.playTitleMusic = function() {
    AudioManager.playBgm($dataSystem.titleBgm);
    AudioManager.stopBgs();
    AudioManager.stopMe();
};

//-----------------------------------------------------------------------------
// 场景_地图 
// Scene_Map
// 
// 地图场景的场景类。 
// The scene class of the map screen.

function Scene_Map() {
    this.initialize.apply(this, arguments);
}

Scene_Map.prototype = Object.create(Scene_Base.prototype);
Scene_Map.prototype.constructor = Scene_Map;

/* 初始化 */
Scene_Map.prototype.initialize = function() {
    Scene_Base.prototype.initialize.call(this);
    this._waitCount = 0;
    this._encounterEffectDuration = 0;
    this._mapLoaded = false;
    this._touchCount = 0;
};

/* 创建 */
Scene_Map.prototype.create = function() {
    Scene_Base.prototype.create.call(this);
    this._transfer = $gamePlayer.isTransferring();
    var mapId = this._transfer ? $gamePlayer.newMapId() : $gameMap.mapId();
    DataManager.loadMapData(mapId);
};

/* 是否准备好 */
Scene_Map.prototype.isReady = function() {
    if (!this._mapLoaded &amp;&amp; DataManager.isMapLoaded()) {
        this.onMapLoaded();
        this._mapLoaded = true;
    }
    return this._mapLoaded &amp;&amp; Scene_Base.prototype.isReady.call(this);
};

/* 当地图加载完 */
Scene_Map.prototype.onMapLoaded = function() {
    if (this._transfer) {
        $gamePlayer.performTransfer();
    }
    this.createDisplayObjects();
};

/* 开始 */
Scene_Map.prototype.start = function() {
    Scene_Base.prototype.start.call(this);
    SceneManager.clearStack();
    if (this._transfer) {
        this.fadeInForTransfer();
        this._mapNameWindow.open();
        $gameMap.autoplay();
    } else if (this.needsFadeIn()) {
        this.startFadeIn(this.fadeSpeed(), false);
    }
    this.menuCalling = false;
};

/* 更新 */
Scene_Map.prototype.update = function() {
    this.updateDestination();
    this.updateMainMultiply();
    if (this.isSceneChangeOk()) {
        this.updateScene();
    } else if (SceneManager.isNextScene(Scene_Battle)) {
        this.updateEncounterEffect();
    }
    this.updateWaitCount();
    Scene_Base.prototype.update.call(this);
};

/* 加倍更新主函数 
 * 一帧内执行两次，即帧率翻倍。
 */
Scene_Map.prototype.updateMainMultiply = function() {
    this.updateMain();
    if (this.isFastForward()) {
        this.updateMain();
    }
};

/* 更新主函数 */
Scene_Map.prototype.updateMain = function() {
    var active = this.isActive();
    $gameMap.update(active);
    $gamePlayer.update(active);
    $gameTimer.update(active);
    $gameScreen.update();
};

/* 是否快进 */
Scene_Map.prototype.isFastForward = function() {
    return ($gameMap.isEventRunning() &amp;&amp; !SceneManager.isSceneChanging() &amp;&amp;
            (Input.isLongPressed('ok') || TouchInput.isLongPressed()));
};

/* 停止 */
Scene_Map.prototype.stop = function() {
    Scene_Base.prototype.stop.call(this);
    $gamePlayer.straighten();
    this._mapNameWindow.close();
    if (this.needsSlowFadeOut()) {
        this.startFadeOut(this.slowFadeSpeed(), false);
    } else if (SceneManager.isNextScene(Scene_Map)) {
        this.fadeOutForTransfer();
    } else if (SceneManager.isNextScene(Scene_Battle)) {
        this.launchBattle();
    }
};

/* 是否繁忙 */
Scene_Map.prototype.isBusy = function() {
    return ((this._messageWindow &amp;&amp; this._messageWindow.isClosing()) ||
            this._waitCount &gt; 0 || this._encounterEffectDuration &gt; 0 ||
            Scene_Base.prototype.isBusy.call(this));
};

/* 结束 */
Scene_Map.prototype.terminate = function() {
    Scene_Base.prototype.terminate.call(this);
    if (!SceneManager.isNextScene(Scene_Battle)) {
        this._spriteset.update();
        this._mapNameWindow.hide();
        SceneManager.snapForBackground();
    } else {
        ImageManager.clearRequest();
    }

    if (SceneManager.isNextScene(Scene_Map)) {
        ImageManager.clearRequest();
    }

    $gameScreen.clearZoom();

    this.removeChild(this._fadeSprite);
    this.removeChild(this._mapNameWindow);
    this.removeChild(this._windowLayer);
    this.removeChild(this._spriteset);
};

/* 是否需要淡入 */
Scene_Map.prototype.needsFadeIn = function() {
    return (SceneManager.isPreviousScene(Scene_Battle) ||
            SceneManager.isPreviousScene(Scene_Load));
};

/* 是否需要缓慢淡出 */
Scene_Map.prototype.needsSlowFadeOut = function() {
    return (SceneManager.isNextScene(Scene_Title) ||
            SceneManager.isNextScene(Scene_Gameover));
};

/* 更新等待计数 */
Scene_Map.prototype.updateWaitCount = function() {
    if (this._waitCount &gt; 0) {
        this._waitCount--;
        return true;
    }
    return false;
};

/* 更新目的地 */
Scene_Map.prototype.updateDestination = function() {
    if (this.isMapTouchOk()) {
        this.processMapTouch();
    } else {
        $gameTemp.clearDestination();
        this._touchCount = 0;
    }
};

/* 是否地图可以触摸 */
Scene_Map.prototype.isMapTouchOk = function() {
    return this.isActive() &amp;&amp; $gamePlayer.canMove();
};

/* 处理地图触摸 */
Scene_Map.prototype.processMapTouch = function() {
    if (TouchInput.isTriggered() || this._touchCount &gt; 0) {
        if (TouchInput.isPressed()) {
            if (this._touchCount === 0 || this._touchCount &gt;= 15) {
                var x = $gameMap.canvasToMapX(TouchInput.x);
                var y = $gameMap.canvasToMapY(TouchInput.y);
                $gameTemp.setDestination(x, y);
            }
            this._touchCount;
        } else {
            this._touchCount = 0;
        }
    }
};

/* 是否场景切换好了 */
Scene_Map.prototype.isSceneChangeOk = function() {
    return this.isActive() &amp;&amp; !$gameMessage.isBusy();
};

/* 更新场景 */
Scene_Map.prototype.updateScene = function() {
    this.checkGameover();
    if (!SceneManager.isSceneChanging()) {
        this.updateTransferPlayer();
    }
    if (!SceneManager.isSceneChanging()) {
        this.updateEncounter();
    }
    if (!SceneManager.isSceneChanging()) {
        this.updateCallMenu();
    }
    if (!SceneManager.isSceneChanging()) {
        this.updateCallDebug();
    }
};

/* 创建显示对象 */
Scene_Map.prototype.createDisplayObjects = function() {
    this.createSpriteset();
    this.createMapNameWindow();
    this.createWindowLayer();
    this.createAllWindows();
};

/* 创建精灵组 */
Scene_Map.prototype.createSpriteset = function() {
    this._spriteset = new Spriteset_Map();
    this.addChild(this._spriteset);
};

/* 创建所有窗口 */
Scene_Map.prototype.createAllWindows = function() {
    this.createMessageWindow();
    this.createScrollTextWindow();
};

/* 创建地图名字窗口 */
Scene_Map.prototype.createMapNameWindow = function() {
    this._mapNameWindow = new Window_MapName();
    this.addChild(this._mapNameWindow);
};

/* 创建信息窗口 */
Scene_Map.prototype.createMessageWindow = function() {
    this._messageWindow = new Window_Message();
    this.addWindow(this._messageWindow);
    this._messageWindow.subWindows().forEach(function(window) {
        this.addWindow(window);
    }, this);
};

/* 创建滚动文字窗口 */
Scene_Map.prototype.createScrollTextWindow = function() {
    this._scrollTextWindow = new Window_ScrollText();
    this.addWindow(this._scrollTextWindow);
};

/* 更新传送玩家 */
Scene_Map.prototype.updateTransferPlayer = function() {
    if ($gamePlayer.isTransferring()) {
        SceneManager.goto(Scene_Map);
    }
};

/* 更新遇敌 */
Scene_Map.prototype.updateEncounter = function() {
   if ($gamePlayer.executeEncounter()) {
       SceneManager.push(Scene_Battle);
   }
};

/* 更新呼叫菜单 */
Scene_Map.prototype.updateCallMenu = function() {
    if (this.isMenuEnabled()) {
        if (this.isMenuCalled()) {
            this.menuCalling = true;
        }
        if (this.menuCalling &amp;&amp; !$gamePlayer.isMoving()) {
            this.callMenu();
        }
    } else {
        this.menuCalling = false;
    }
};

/* 是否菜单启用 */
Scene_Map.prototype.isMenuEnabled = function() {
    return $gameSystem.isMenuEnabled() &amp;&amp; !$gameMap.isEventRunning();
};

/* 更新菜单被呼叫 */
Scene_Map.prototype.isMenuCalled = function() {
    return Input.isTriggered('menu') || TouchInput.isCancelled();
};

/* 呼叫菜单 */
Scene_Map.prototype.callMenu = function() {
    SoundManager.playOk();
    SceneManager.push(Scene_Menu);
    Window_MenuCommand.initCommandPosition();
    $gameTemp.clearDestination();
    this._mapNameWindow.hide();
    this._waitCount = 2;
};

/* 更新呼叫调试 */
Scene_Map.prototype.updateCallDebug = function() {
    if (this.isDebugCalled()) {
        SceneManager.push(Scene_Debug);
    }
};

/* 是否调试被呼叫 */
Scene_Map.prototype.isDebugCalled = function() {
    return Input.isTriggered('debug') &amp;&amp; $gameTemp.isPlaytest();
};

/* 淡入传送 */
Scene_Map.prototype.fadeInForTransfer = function() {
    var fadeType = $gamePlayer.fadeType();
    switch (fadeType) {
    case 0: case 1:
        this.startFadeIn(this.fadeSpeed(), fadeType === 1);
        break;
    }
};

/* 淡出传送 */
Scene_Map.prototype.fadeOutForTransfer = function() {
    var fadeType = $gamePlayer.fadeType();
    switch (fadeType) {
    case 0: case 1:
        this.startFadeOut(this.fadeSpeed(), fadeType === 1);
        break;
    }
};

/* 发起战斗 */
Scene_Map.prototype.launchBattle = function() {
    BattleManager.saveBgmAndBgs();
    this.stopAudioOnBattleStart();
    SoundManager.playBattleStart();
    this.startEncounterEffect();
    this._mapNameWindow.hide();
};

/* 当战斗开始停止音频 */
Scene_Map.prototype.stopAudioOnBattleStart = function() {
    if (!AudioManager.isCurrentBgm($gameSystem.battleBgm())) {
        AudioManager.stopBgm();
    }
    AudioManager.stopBgs();
    AudioManager.stopMe();
    AudioManager.stopSe();
};

/* 开始遇敌效果 */
Scene_Map.prototype.startEncounterEffect = function() {
    this._spriteset.hideCharacters();
    this._encounterEffectDuration = this.encounterEffectSpeed();
};

/* 更新遇敌效果 */
Scene_Map.prototype.updateEncounterEffect = function() {
    if (this._encounterEffectDuration &gt; 0) {
        this._encounterEffectDuration--;
        var speed = this.encounterEffectSpeed();
        var n = speed - this._encounterEffectDuration;
        var p = n / speed;
        var q = ((p - 1) * 20 * p + 5) * p + 1;
        var zoomX = $gamePlayer.screenX();
        var zoomY = $gamePlayer.screenY() - 24;
        if (n === 2) {
            $gameScreen.setZoom(zoomX, zoomY, 1);
            this.snapForBattleBackground();
            this.startFlashForEncounter(speed / 2);
        }
        $gameScreen.setZoom(zoomX, zoomY, q);
        if (n === Math.floor(speed / 6)) {
            this.startFlashForEncounter(speed / 2);
        }
        if (n === Math.floor(speed / 2)) {
            BattleManager.playBattleBgm();
            this.startFadeOut(this.fadeSpeed());
        }
    }
};

/* 快照作为战斗背景 */
Scene_Map.prototype.snapForBattleBackground = function() {
    this._windowLayer.visible = false;
    SceneManager.snapForBackground();
    this._windowLayer.visible = true;
};

/* 遇敌开始闪烁 */
Scene_Map.prototype.startFlashForEncounter = function(duration) {
    var color = [255, 255, 255, 255];
    $gameScreen.startFlash(color, duration);
};

/* 遇敌效果速度 */
Scene_Map.prototype.encounterEffectSpeed = function() {
    return 60;
};

//-----------------------------------------------------------------------------
// 场景_菜单基础 
// Scene_MenuBase
//
// 所有菜单类型场景的父类。 
// The superclass of all the menu-type scenes.

function Scene_MenuBase() {
    this.initialize.apply(this, arguments);
}

Scene_MenuBase.prototype = Object.create(Scene_Base.prototype);
Scene_MenuBase.prototype.constructor = Scene_MenuBase;

/* 初始化 */
Scene_MenuBase.prototype.initialize = function() {
    Scene_Base.prototype.initialize.call(this);
};

/* 创建 */
Scene_MenuBase.prototype.create = function() {
    Scene_Base.prototype.create.call(this);
    this.createBackground();
    this.updateActor();
    this.createWindowLayer();
};

/* 角色 */
Scene_MenuBase.prototype.actor = function() {
    return this._actor;
};

/* 更新角色 */
Scene_MenuBase.prototype.updateActor = function() {
    this._actor = $gameParty.menuActor();
};

/* 创建背景 */
Scene_MenuBase.prototype.createBackground = function() {
    this._backgroundSprite = new Sprite();
    this._backgroundSprite.bitmap = SceneManager.backgroundBitmap();
    this.addChild(this._backgroundSprite);
};

/* 设置背景不透明度 */
Scene_MenuBase.prototype.setBackgroundOpacity = function(opacity) {
    this._backgroundSprite.opacity = opacity;
};

/* 创建帮助窗口 */
Scene_MenuBase.prototype.createHelpWindow = function() {
    this._helpWindow = new Window_Help();
    this.addWindow(this._helpWindow);
};

/* 下一个角色 */
Scene_MenuBase.prototype.nextActor = function() {
    $gameParty.makeMenuActorNext();
    this.updateActor();
    this.onActorChange();
};

/* 上一个角色 */
Scene_MenuBase.prototype.previousActor = function() {
    $gameParty.makeMenuActorPrevious();
    this.updateActor();
    this.onActorChange();
};

/* 当角色改变 */
Scene_MenuBase.prototype.onActorChange = function() {
};

//-----------------------------------------------------------------------------
// 场景_菜单 
// Scene_Menu
//
// 菜单画面的场景类。 
// The scene class of the menu screen.

function Scene_Menu() {
    this.initialize.apply(this, arguments);
}

Scene_Menu.prototype = Object.create(Scene_MenuBase.prototype);
Scene_Menu.prototype.constructor = Scene_Menu;

/* 初始化 */
Scene_Menu.prototype.initialize = function() {
    Scene_MenuBase.prototype.initialize.call(this);
};

/* 创建 */
Scene_Menu.prototype.create = function() {
    Scene_MenuBase.prototype.create.call(this);
    this.createCommandWindow();
    this.createGoldWindow();
    this.createStatusWindow();
};

/* 开始 */
Scene_Menu.prototype.start = function() {
    Scene_MenuBase.prototype.start.call(this);
    this._statusWindow.refresh();
};

/* 创建指令窗口 */
Scene_Menu.prototype.createCommandWindow = function() {
    this._commandWindow = new Window_MenuCommand(0, 0);
    this._commandWindow.setHandler('item',      this.commandItem.bind(this));
    this._commandWindow.setHandler('skill',     this.commandPersonal.bind(this));
    this._commandWindow.setHandler('equip',     this.commandPersonal.bind(this));
    this._commandWindow.setHandler('status',    this.commandPersonal.bind(this));
    this._commandWindow.setHandler('formation', this.commandFormation.bind(this));
    this._commandWindow.setHandler('options',   this.commandOptions.bind(this));
    this._commandWindow.setHandler('save',      this.commandSave.bind(this));
    this._commandWindow.setHandler('gameEnd',   this.commandGameEnd.bind(this));
    this._commandWindow.setHandler('cancel',    this.popScene.bind(this));
    this.addWindow(this._commandWindow);
};

/* 创建金钱窗口 */
Scene_Menu.prototype.createGoldWindow = function() {
    this._goldWindow = new Window_Gold(0, 0);
    this._goldWindow.y = Graphics.boxHeight - this._goldWindow.height;
    this.addWindow(this._goldWindow);
};

/* 创建状态窗口 */
Scene_Menu.prototype.createStatusWindow = function() {
    this._statusWindow = new Window_MenuStatus(this._commandWindow.width, 0);
    this._statusWindow.reserveFaceImages();
    this.addWindow(this._statusWindow);
};

/* 物品的指令 */
Scene_Menu.prototype.commandItem = function() {
    SceneManager.push(Scene_Item);
};

/* 个人的指令 */
Scene_Menu.prototype.commandPersonal = function() {
    this._statusWindow.setFormationMode(false);
    this._statusWindow.selectLast();
    this._statusWindow.activate();
    this._statusWindow.setHandler('ok',     this.onPersonalOk.bind(this));
    this._statusWindow.setHandler('cancel', this.onPersonalCancel.bind(this));
};

/* 整队的指令 */
Scene_Menu.prototype.commandFormation = function() {
    this._statusWindow.setFormationMode(true);
    this._statusWindow.selectLast();
    this._statusWindow.activate();
    this._statusWindow.setHandler('ok',     this.onFormationOk.bind(this));
    this._statusWindow.setHandler('cancel', this.onFormationCancel.bind(this));
};

/* 选项的指令 */
Scene_Menu.prototype.commandOptions = function() {
    SceneManager.push(Scene_Options);
};

/* 存档的指令 */
Scene_Menu.prototype.commandSave = function() {
    SceneManager.push(Scene_Save);
};

/* 游戏结束的指令 */
Scene_Menu.prototype.commandGameEnd = function() {
    SceneManager.push(Scene_GameEnd);
};

/* 当个人确定 */
Scene_Menu.prototype.onPersonalOk = function() {
    switch (this._commandWindow.currentSymbol()) {
    case 'skill':
        SceneManager.push(Scene_Skill);
        break;
    case 'equip':
        SceneManager.push(Scene_Equip);
        break;
    case 'status':
        SceneManager.push(Scene_Status);
        break;
    }
};

/* 当个人取消 */
Scene_Menu.prototype.onPersonalCancel = function() {
    this._statusWindow.deselect();
    this._commandWindow.activate();
};

/* 当整队确定 */
Scene_Menu.prototype.onFormationOk = function() {
    var index = this._statusWindow.index();
    var actor = $gameParty.members()[index];
    var pendingIndex = this._statusWindow.pendingIndex();
    if (pendingIndex &gt;= 0) {
        $gameParty.swapOrder(index, pendingIndex);
        this._statusWindow.setPendingIndex(-1);
        this._statusWindow.redrawItem(index);
    } else {
        this._statusWindow.setPendingIndex(index);
    }
    this._statusWindow.activate();
};

/* 当整队取消 */
Scene_Menu.prototype.onFormationCancel = function() {
    if (this._statusWindow.pendingIndex() &gt;= 0) {
        this._statusWindow.setPendingIndex(-1);
        this._statusWindow.activate();
    } else {
        this._statusWindow.deselect();
        this._commandWindow.activate();
    }
};

//-----------------------------------------------------------------------------
// 场景_项目基础 
// Scene_ItemBase
//
// Scene_Item 和 Scene_Skill 的父类。 
// The superclass of Scene_Item and Scene_Skill.

function Scene_ItemBase() {
    this.initialize.apply(this, arguments);
}

Scene_ItemBase.prototype = Object.create(Scene_MenuBase.prototype);
Scene_ItemBase.prototype.constructor = Scene_ItemBase;

/* 初始化 */
Scene_ItemBase.prototype.initialize = function() {
    Scene_MenuBase.prototype.initialize.call(this);
};

/* 创建 */
Scene_ItemBase.prototype.create = function() {
    Scene_MenuBase.prototype.create.call(this);
};

/* 创建角色窗口 */
Scene_ItemBase.prototype.createActorWindow = function() {
    this._actorWindow = new Window_MenuActor();
    this._actorWindow.setHandler('ok',     this.onActorOk.bind(this));
    this._actorWindow.setHandler('cancel', this.onActorCancel.bind(this));
    this.addWindow(this._actorWindow);
};

/* 项目 */
Scene_ItemBase.prototype.item = function() {
    return this._itemWindow.item();
};

/* 使用者 */
Scene_ItemBase.prototype.user = function() {
    return null;
};

/* 是否光标在左边
 * 物品场景和技能插件只有两列，所以光标不是左边就是右边，影响使用物品/技能后的子窗口位置。
 */
Scene_ItemBase.prototype.isCursorLeft = function() {
    return this._itemWindow.index() % 2 === 0;
};

/* 显示子窗口 */
Scene_ItemBase.prototype.showSubWindow = function(window) {
    window.x = this.isCursorLeft() ? Graphics.boxWidth - window.width : 0;
    window.show();
    window.activate();
};

/* 隐藏子窗口 */
Scene_ItemBase.prototype.hideSubWindow = function(window) {
    window.hide();
    window.deactivate();
    this.activateItemWindow();
};

/* 当角色确定 */
Scene_ItemBase.prototype.onActorOk = function() {
    if (this.canUse()) {
        this.useItem();
    } else {
        SoundManager.playBuzzer();
    }
};

/* 当角色取消 */
Scene_ItemBase.prototype.onActorCancel = function() {
    this.hideSubWindow(this._actorWindow);
};

/* 确定项目 */
Scene_ItemBase.prototype.determineItem = function() {
    var action = new Game_Action(this.user());
    var item = this.item();
    action.setItemObject(item);
    if (action.isForFriend()) {
        this.showSubWindow(this._actorWindow);
        this._actorWindow.selectForItem(this.item());
    } else {
        this.useItem();
        this.activateItemWindow();
    }
};

/* 使用项目 */
Scene_ItemBase.prototype.useItem = function() {
    this.playSeForItem();
    this.user().useItem(this.item());
    this.applyItem();
    this.checkCommonEvent();
    this.checkGameover();
    this._actorWindow.refresh();
};

/* 激活项目窗口 */
Scene_ItemBase.prototype.activateItemWindow = function() {
    this._itemWindow.refresh();
    this._itemWindow.activate();
};

/* 项目的目标角色 */
Scene_ItemBase.prototype.itemTargetActors = function() {
    var action = new Game_Action(this.user());
    action.setItemObject(this.item());
    if (!action.isForFriend()) {
        return [];
    } else if (action.isForAll()) {
        return $gameParty.members();
    } else {
        return [$gameParty.members()[this._actorWindow.index()]];
    }
};

/* 是否能使用 */
Scene_ItemBase.prototype.canUse = function() {
    return this.user().canUse(this.item()) &amp;&amp; this.isItemEffectsValid();
};

/* 是否项目效果有效 */
Scene_ItemBase.prototype.isItemEffectsValid = function() {
    var action = new Game_Action(this.user());
    action.setItemObject(this.item());
    return this.itemTargetActors().some(function(target) {
        return action.testApply(target);
    }, this);
};

/* 执行项目 */
Scene_ItemBase.prototype.applyItem = function() {
    var action = new Game_Action(this.user());
    action.setItemObject(this.item());
    this.itemTargetActors().forEach(function(target) {
        for (var i = 0; i &lt; action.numRepeats(); i) {
            action.apply(target);
        }
    }, this);
    action.applyGlobal();
};

/* 检测公共事件 */
Scene_ItemBase.prototype.checkCommonEvent = function() {
    if ($gameTemp.isCommonEventReserved()) {
        SceneManager.goto(Scene_Map);
    }
};

//-----------------------------------------------------------------------------
// 场景_物品 
// Scene_Item
//
// 物品画面的场景类。 
// The scene class of the item screen.

function Scene_Item() {
    this.initialize.apply(this, arguments);
}

Scene_Item.prototype = Object.create(Scene_ItemBase.prototype);
Scene_Item.prototype.constructor = Scene_Item;

/* 初始化 */
Scene_Item.prototype.initialize = function() {
    Scene_ItemBase.prototype.initialize.call(this);
};

/* 创建 */
Scene_Item.prototype.create = function() {
    Scene_ItemBase.prototype.create.call(this);
    this.createHelpWindow();
    this.createCategoryWindow();
    this.createItemWindow();
    this.createActorWindow();
};

/* 创建类型窗口 */
Scene_Item.prototype.createCategoryWindow = function() {
    this._categoryWindow = new Window_ItemCategory();
    this._categoryWindow.setHelpWindow(this._helpWindow);
    this._categoryWindow.y = this._helpWindow.height;
    this._categoryWindow.setHandler('ok',     this.onCategoryOk.bind(this));
    this._categoryWindow.setHandler('cancel', this.popScene.bind(this));
    this.addWindow(this._categoryWindow);
};

/* 创建项目窗口 */
Scene_Item.prototype.createItemWindow = function() {
    var wy = this._categoryWindow.y + this._categoryWindow.height;
    var wh = Graphics.boxHeight - wy;
    this._itemWindow = new Window_ItemList(0, wy, Graphics.boxWidth, wh);
    this._itemWindow.setHelpWindow(this._helpWindow);
    this._itemWindow.setHandler('ok',     this.onItemOk.bind(this));
    this._itemWindow.setHandler('cancel', this.onItemCancel.bind(this));
    this.addWindow(this._itemWindow);
    this._categoryWindow.setItemWindow(this._itemWindow);
};

/* 使用者 */
Scene_Item.prototype.user = function() {
    var members = $gameParty.movableMembers();
    var bestActor = members[0];
    var bestPha = 0;
    for (var i = 0; i &lt; members.length; i+) {
        if (members[i].pha &gt; bestPha) {
            bestPha = members[i].pha;
            bestActor = members[i];
        }
    }
    return bestActor;
};

/* 当类型确定 */
Scene_Item.prototype.onCategoryOk = function() {
    this._itemWindow.activate();
    this._itemWindow.selectLast();
};

/* 当项目确定 */
Scene_Item.prototype.onItemOk = function() {
    $gameParty.setLastItem(this.item());
    this.determineItem();
};

/* 当项目取消 */
Scene_Item.prototype.onItemCancel = function() {
    this._itemWindow.deselect();
    this._categoryWindow.activate();
};

/* 播放项目的音效 */
Scene_Item.prototype.playSeForItem = function() {
    SoundManager.playUseItem();
};

/* 使用项目 */
Scene_Item.prototype.useItem = function() {
    Scene_ItemBase.prototype.useItem.call(this);
    this._itemWindow.redrawCurrentItem();
};

//-----------------------------------------------------------------------------
// 场景_技能 
// Scene_Skill
//
// 技能画面的场景类。 
// The scene class of the skill screen.

function Scene_Skill() {
    this.initialize.apply(this, arguments);
}

Scene_Skill.prototype = Object.create(Scene_ItemBase.prototype);
Scene_Skill.prototype.constructor = Scene_Skill;

/* 初始化 */
Scene_Skill.prototype.initialize = function() {
    Scene_ItemBase.prototype.initialize.call(this);
};

/* 创建 */
Scene_Skill.prototype.create = function() {
    Scene_ItemBase.prototype.create.call(this);
    this.createHelpWindow();
    this.createSkillTypeWindow();
    this.createStatusWindow();
    this.createItemWindow();
    this.createActorWindow();
};

/* 开始 */
Scene_Skill.prototype.start = function() {
    Scene_ItemBase.prototype.start.call(this);
    this.refreshActor();
};

/* 创建技能类型窗口 */
Scene_Skill.prototype.createSkillTypeWindow = function() {
    var wy = this._helpWindow.height;
    this._skillTypeWindow = new Window_SkillType(0, wy);
    this._skillTypeWindow.setHelpWindow(this._helpWindow);
    this._skillTypeWindow.setHandler('skill',    this.commandSkill.bind(this));
    this._skillTypeWindow.setHandler('cancel',   this.popScene.bind(this));
    this._skillTypeWindow.setHandler('pagedown', this.nextActor.bind(this));
    this._skillTypeWindow.setHandler('pageup',   this.previousActor.bind(this));
    this.addWindow(this._skillTypeWindow);
};

/* 创建状态窗口 */
Scene_Skill.prototype.createStatusWindow = function() {
    var wx = this._skillTypeWindow.width;
    var wy = this._helpWindow.height;
    var ww = Graphics.boxWidth - wx;
    var wh = this._skillTypeWindow.height;
    this._statusWindow = new Window_SkillStatus(wx, wy, ww, wh);
    this._statusWindow.reserveFaceImages();
    this.addWindow(this._statusWindow);
};

/* 创建项目窗口 */
Scene_Skill.prototype.createItemWindow = function() {
    var wx = 0;
    var wy = this._statusWindow.y + this._statusWindow.height;
    var ww = Graphics.boxWidth;
    var wh = Graphics.boxHeight - wy;
    this._itemWindow = new Window_SkillList(wx, wy, ww, wh);
    this._itemWindow.setHelpWindow(this._helpWindow);
    this._itemWindow.setHandler('ok',     this.onItemOk.bind(this));
    this._itemWindow.setHandler('cancel', this.onItemCancel.bind(this));
    this._skillTypeWindow.setSkillWindow(this._itemWindow);
    this.addWindow(this._itemWindow);
};

/* 刷新角色 */
Scene_Skill.prototype.refreshActor = function() {
    var actor = this.actor();
    this._skillTypeWindow.setActor(actor);
    this._statusWindow.setActor(actor);
    this._itemWindow.setActor(actor);
};

/* 使用者 */
Scene_Skill.prototype.user = function() {
    return this.actor();
};

/* 技能的指令 */
Scene_Skill.prototype.commandSkill = function() {
    this._itemWindow.activate();
    this._itemWindow.selectLast();
};

/* 当项目确定 */
Scene_Skill.prototype.onItemOk = function() {
    this.actor().setLastMenuSkill(this.item());
    this.determineItem();
};

/* 当项目取消 */
Scene_Skill.prototype.onItemCancel = function() {
    this._itemWindow.deselect();
    this._skillTypeWindow.activate();
};

/* 播放项目的音效 */
Scene_Skill.prototype.playSeForItem = function() {
    SoundManager.playUseSkill();
};

/* 使用项目 */
Scene_Skill.prototype.useItem = function() {
    Scene_ItemBase.prototype.useItem.call(this);
    this._statusWindow.refresh();
    this._itemWindow.refresh();
};

/* 当角色改变 */
Scene_Skill.prototype.onActorChange = function() {
    this.refreshActor();
    this._skillTypeWindow.activate();
};

//-----------------------------------------------------------------------------
// 场景_装备 
// Scene_Equip
//
// 装备画面的场景类。 
// The scene class of the equipment screen.

function Scene_Equip() {
    this.initialize.apply(this, arguments);
}

Scene_Equip.prototype = Object.create(Scene_MenuBase.prototype);
Scene_Equip.prototype.constructor = Scene_Equip;

/* 初始化 */
Scene_Equip.prototype.initialize = function() {
    Scene_MenuBase.prototype.initialize.call(this);
};

/* 创建 */
Scene_Equip.prototype.create = function() {
    Scene_MenuBase.prototype.create.call(this);
    this.createHelpWindow();
    this.createStatusWindow();
    this.createCommandWindow();
    this.createSlotWindow();
    this.createItemWindow();
    this.refreshActor();
};

/* 创建状态窗口 */
Scene_Equip.prototype.createStatusWindow = function() {
    this._statusWindow = new Window_EquipStatus(0, this._helpWindow.height);
    this.addWindow(this._statusWindow);
};

/* 创建指令窗口 */
Scene_Equip.prototype.createCommandWindow = function() {
    var wx = this._statusWindow.width;
    var wy = this._helpWindow.height;
    var ww = Graphics.boxWidth - this._statusWindow.width;
    this._commandWindow = new Window_EquipCommand(wx, wy, ww);
    this._commandWindow.setHelpWindow(this._helpWindow);
    this._commandWindow.setHandler('equip',    this.commandEquip.bind(this));
    this._commandWindow.setHandler('optimize', this.commandOptimize.bind(this));
    this._commandWindow.setHandler('clear',    this.commandClear.bind(this));
    this._commandWindow.setHandler('cancel',   this.popScene.bind(this));
    this._commandWindow.setHandler('pagedown', this.nextActor.bind(this));
    this._commandWindow.setHandler('pageup',   this.previousActor.bind(this));
    this.addWindow(this._commandWindow);
};

/* 创建插槽窗口 */
Scene_Equip.prototype.createSlotWindow = function() {
    var wx = this._statusWindow.width;
    var wy = this._commandWindow.y + this._commandWindow.height;
    var ww = Graphics.boxWidth - this._statusWindow.width;
    var wh = this._statusWindow.height - this._commandWindow.height;
    this._slotWindow = new Window_EquipSlot(wx, wy, ww, wh);
    this._slotWindow.setHelpWindow(this._helpWindow);
    this._slotWindow.setStatusWindow(this._statusWindow);
    this._slotWindow.setHandler('ok',       this.onSlotOk.bind(this));
    this._slotWindow.setHandler('cancel',   this.onSlotCancel.bind(this));
    this.addWindow(this._slotWindow);
};

/* 创建项目窗口 */
Scene_Equip.prototype.createItemWindow = function() {
    var wx = 0;
    var wy = this._statusWindow.y + this._statusWindow.height;
    var ww = Graphics.boxWidth;
    var wh = Graphics.boxHeight - wy;
    this._itemWindow = new Window_EquipItem(wx, wy, ww, wh);
    this._itemWindow.setHelpWindow(this._helpWindow);
    this._itemWindow.setStatusWindow(this._statusWindow);
    this._itemWindow.setHandler('ok',     this.onItemOk.bind(this));
    this._itemWindow.setHandler('cancel', this.onItemCancel.bind(this));
    this._slotWindow.setItemWindow(this._itemWindow);
    this.addWindow(this._itemWindow);
};

/* 刷新角色 */
Scene_Equip.prototype.refreshActor = function() {
    var actor = this.actor();
    this._statusWindow.setActor(actor);
    this._slotWindow.setActor(actor);
    this._itemWindow.setActor(actor);
};

/* 装备的指令 */
Scene_Equip.prototype.commandEquip = function() {
    this._slotWindow.activate();
    this._slotWindow.select(0);
};

/* 最强装备的指令 */
Scene_Equip.prototype.commandOptimize = function() {
    SoundManager.playEquip();
    this.actor().optimizeEquipments();
    this._statusWindow.refresh();
    this._slotWindow.refresh();
    this._commandWindow.activate();
};

/* 清空的指令 */
Scene_Equip.prototype.commandClear = function() {
    SoundManager.playEquip();
    this.actor().clearEquipments();
    this._statusWindow.refresh();
    this._slotWindow.refresh();
    this._commandWindow.activate();
};

/* 当插槽确定 */
Scene_Equip.prototype.onSlotOk = function() {
    this._itemWindow.activate();
    this._itemWindow.select(0);
};

/* 当插槽取消 */
Scene_Equip.prototype.onSlotCancel = function() {
    this._slotWindow.deselect();
    this._commandWindow.activate();
};

/* 当项目确定 */
Scene_Equip.prototype.onItemOk = function() {
    SoundManager.playEquip();
    this.actor().changeEquip(this._slotWindow.index(), this._itemWindow.item());
    this._slotWindow.activate();
    this._slotWindow.refresh();
    this._itemWindow.deselect();
    this._itemWindow.refresh();
    this._statusWindow.refresh();
};

/* 当项目取消 */
Scene_Equip.prototype.onItemCancel = function() {
    this._slotWindow.activate();
    this._itemWindow.deselect();
};

/* 当角色改变 */
Scene_Equip.prototype.onActorChange = function() {
    this.refreshActor();
    this._commandWindow.activate();
};

//-----------------------------------------------------------------------------
// 场景_状态 
// Scene_Status
//
// 状态画面的场景类。 
// The scene class of the status screen.

function Scene_Status() {
    this.initialize.apply(this, arguments);
}

Scene_Status.prototype = Object.create(Scene_MenuBase.prototype);
Scene_Status.prototype.constructor = Scene_Status;

/* 初始化 */
Scene_Status.prototype.initialize = function() {
    Scene_MenuBase.prototype.initialize.call(this);
};

/* 创建 */
Scene_Status.prototype.create = function() {
    Scene_MenuBase.prototype.create.call(this);
    this._statusWindow = new Window_Status();
    this._statusWindow.setHandler('cancel',   this.popScene.bind(this));
    this._statusWindow.setHandler('pagedown', this.nextActor.bind(this));
    this._statusWindow.setHandler('pageup',   this.previousActor.bind(this));
    this._statusWindow.reserveFaceImages();
    this.addWindow(this._statusWindow);
};

/* 开始 */
Scene_Status.prototype.start = function() {
    Scene_MenuBase.prototype.start.call(this);
    this.refreshActor();
};

/* 刷新角色 */
Scene_Status.prototype.refreshActor = function() {
    var actor = this.actor();
    this._statusWindow.setActor(actor);
};

/* 当角色改变 */
Scene_Status.prototype.onActorChange = function() {
    this.refreshActor();
    this._statusWindow.activate();
};

//-----------------------------------------------------------------------------
// 场景_设置 
// Scene_Options
//
// 设置画面的场景类。 
// The scene class of the options screen.

function Scene_Options() {
    this.initialize.apply(this, arguments);
}

Scene_Options.prototype = Object.create(Scene_MenuBase.prototype);
Scene_Options.prototype.constructor = Scene_Options;

/* 初始化 */
Scene_Options.prototype.initialize = function() {
    Scene_MenuBase.prototype.initialize.call(this);
};

/* 创建 */
Scene_Options.prototype.create = function() {
    Scene_MenuBase.prototype.create.call(this);
    this.createOptionsWindow();
};

/* 结束 */
Scene_Options.prototype.terminate = function() {
    Scene_MenuBase.prototype.terminate.call(this);
    ConfigManager.save();
};

/* 创建设置窗口 */
Scene_Options.prototype.createOptionsWindow = function() {
    this._optionsWindow = new Window_Options();
    this._optionsWindow.setHandler('cancel', this.popScene.bind(this));
    this.addWindow(this._optionsWindow);
};

//-----------------------------------------------------------------------------
// 场景_文件 
// Scene_File
//
// Scene_Save 和 Scene_Load 的父类。 
// The superclass of Scene_Save and Scene_Load.

function Scene_File() {
    this.initialize.apply(this, arguments);
}

Scene_File.prototype = Object.create(Scene_MenuBase.prototype);
Scene_File.prototype.constructor = Scene_File;

/* 初始化 */
Scene_File.prototype.initialize = function() {
    Scene_MenuBase.prototype.initialize.call(this);
};

/* 创建 */
Scene_File.prototype.create = function() {
    Scene_MenuBase.prototype.create.call(this);
    DataManager.loadAllSavefileImages();
    this.createHelpWindow();
    this.createListWindow();
};

/* 开始 */
Scene_File.prototype.start = function() {
    Scene_MenuBase.prototype.start.call(this);
    this._listWindow.refresh();
};

/* 存档 ID */
Scene_File.prototype.savefileId = function() {
    return this._listWindow.index() + 1;
};

/* 创建帮助窗口 */
Scene_File.prototype.createHelpWindow = function() {
    this._helpWindow = new Window_Help(1);
    this._helpWindow.setText(this.helpWindowText());
    this.addWindow(this._helpWindow);
};

/* 创建列表窗口 */
Scene_File.prototype.createListWindow = function() {
    var x = 0;
    var y = this._helpWindow.height;
    var width = Graphics.boxWidth;
    var height = Graphics.boxHeight - y;
    this._listWindow = new Window_SavefileList(x, y, width, height);
    this._listWindow.setHandler('ok',     this.onSavefileOk.bind(this));
    this._listWindow.setHandler('cancel', this.popScene.bind(this));
    this._listWindow.select(this.firstSavefileIndex());
    this._listWindow.setTopRow(this.firstSavefileIndex() - 2);
    this._listWindow.setMode(this.mode());
    this._listWindow.refresh();
    this.addWindow(this._listWindow);
};

/* 模式 */
Scene_File.prototype.mode = function() {
    return null;
};

/* 激活列表窗口 */
Scene_File.prototype.activateListWindow = function() {
    this._listWindow.activate();
};

/* 帮助窗口文本 */
Scene_File.prototype.helpWindowText = function() {
    return '';
};

/* 第一个存档索引 */
Scene_File.prototype.firstSavefileIndex = function() {
    return 0;
};

/* 当存档确定 */
Scene_File.prototype.onSavefileOk = function() {
};

//-----------------------------------------------------------------------------
// 场景_存档 
// Scene_Save
//
// 存档画面的场景类。 
// The scene class of the save screen.

function Scene_Save() {
    this.initialize.apply(this, arguments);
}

Scene_Save.prototype = Object.create(Scene_File.prototype);
Scene_Save.prototype.constructor = Scene_Save;

/* 初始化 */
Scene_Save.prototype.initialize = function() {
    Scene_File.prototype.initialize.call(this);
};

/* 模式 */
Scene_Save.prototype.mode = function() {
    return 'save';
};

/* 帮助窗口文本 */
Scene_Save.prototype.helpWindowText = function() {
    return TextManager.saveMessage;
};

/* 第一个存档索引 */
Scene_Save.prototype.firstSavefileIndex = function() {
    return DataManager.lastAccessedSavefileId() - 1;
};

/* 当存档确定 */
Scene_Save.prototype.onSavefileOk = function() {
    Scene_File.prototype.onSavefileOk.call(this);
    $gameSystem.onBeforeSave();
    if (DataManager.saveGame(this.savefileId())) {
        this.onSaveSuccess();
    } else {
        this.onSaveFailure();
    }
};

/* 当保存成功 */
Scene_Save.prototype.onSaveSuccess = function() {
    SoundManager.playSave();
	StorageManager.cleanBackup(this.savefileId());
    this.popScene();
};

/* 当保存失败 */
Scene_Save.prototype.onSaveFailure = function() {
    SoundManager.playBuzzer();
    this.activateListWindow();
};

//-----------------------------------------------------------------------------
// 场景_读档 
// Scene_Load
//
// 读档画面的场景类。 
// The scene class of the load screen.

function Scene_Load() {
    this.initialize.apply(this, arguments);
}

Scene_Load.prototype = Object.create(Scene_File.prototype);
Scene_Load.prototype.constructor = Scene_Load;

/* 初始化 */
Scene_Load.prototype.initialize = function() {
    Scene_File.prototype.initialize.call(this);
    this._loadSuccess = false;
};

/* 结束 */
Scene_Load.prototype.terminate = function() {
    Scene_File.prototype.terminate.call(this);
    if (this._loadSuccess) {
        $gameSystem.onAfterLoad();
    }
};

/* 模式 */
Scene_Load.prototype.mode = function() {
    return 'load';
};

/* 帮助窗口文本 */
Scene_Load.prototype.helpWindowText = function() {
    return TextManager.loadMessage;
};

/* 第一个存档索引 */
Scene_Load.prototype.firstSavefileIndex = function() {
    return DataManager.latestSavefileId() - 1;
};

/* 当存档确定 */
Scene_Load.prototype.onSavefileOk = function() {
    Scene_File.prototype.onSavefileOk.call(this);
    if (DataManager.loadGame(this.savefileId())) {
        this.onLoadSuccess();
    } else {
        this.onLoadFailure();
    }
};

/* 当加载成功 */
Scene_Load.prototype.onLoadSuccess = function() {
    SoundManager.playLoad();
    this.fadeOutAll();
    this.reloadMapIfUpdated();
    SceneManager.goto(Scene_Map);
    this._loadSuccess = true;
};

/* 当加载失败 */
Scene_Load.prototype.onLoadFailure = function() {
    SoundManager.playBuzzer();
    this.activateListWindow();
};

/* 如果更新则重载地图 */
Scene_Load.prototype.reloadMapIfUpdated = function() {
    if ($gameSystem.versionId() !== $dataSystem.versionId) {
        $gamePlayer.reserveTransfer($gameMap.mapId(), $gamePlayer.x, $gamePlayer.y);
        $gamePlayer.requestMapReload();
    }
};

//-----------------------------------------------------------------------------
// 场景_游戏结束 
// Scene_GameEnd
//
// 游戏结束画面的场景类。 
// The scene class of the game end screen.

function Scene_GameEnd() {
    this.initialize.apply(this, arguments);
}

Scene_GameEnd.prototype = Object.create(Scene_MenuBase.prototype);
Scene_GameEnd.prototype.constructor = Scene_GameEnd;

/* 初始化 */
Scene_GameEnd.prototype.initialize = function() {
    Scene_MenuBase.prototype.initialize.call(this);
};

/* 创建 */
Scene_GameEnd.prototype.create = function() {
    Scene_MenuBase.prototype.create.call(this);
    this.createCommandWindow();
};

/* 停止 */
Scene_GameEnd.prototype.stop = function() {
    Scene_MenuBase.prototype.stop.call(this);
    this._commandWindow.close();
};

/* 创建背景 */
Scene_GameEnd.prototype.createBackground = function() {
    Scene_MenuBase.prototype.createBackground.call(this);
    this.setBackgroundOpacity(128);
};

/* 创建指令窗口 */
Scene_GameEnd.prototype.createCommandWindow = function() {
    this._commandWindow = new Window_GameEnd();
    this._commandWindow.setHandler('toTitle',  this.commandToTitle.bind(this));
    this._commandWindow.setHandler('cancel',   this.popScene.bind(this));
    this.addWindow(this._commandWindow);
};

/* 回到标题的指令 */
Scene_GameEnd.prototype.commandToTitle = function() {
    this.fadeOutAll();
    SceneManager.goto(Scene_Title);
};

//-----------------------------------------------------------------------------
// 场景_商店 
// Scene_Shop
//
// 商店画面的场景类。 
// The scene class of the shop screen.

function Scene_Shop() {
    this.initialize.apply(this, arguments);
}

Scene_Shop.prototype = Object.create(Scene_MenuBase.prototype);
Scene_Shop.prototype.constructor = Scene_Shop;

/* 初始化 */
Scene_Shop.prototype.initialize = function() {
    Scene_MenuBase.prototype.initialize.call(this);
};

/* 准备 */
Scene_Shop.prototype.prepare = function(goods, purchaseOnly) {
    this._goods = goods;
    this._purchaseOnly = purchaseOnly;
    this._item = null;
};

/* 创建 */
Scene_Shop.prototype.create = function() {
    Scene_MenuBase.prototype.create.call(this);
    this.createHelpWindow();
    this.createGoldWindow();
    this.createCommandWindow();
    this.createDummyWindow();
    this.createNumberWindow();
    this.createStatusWindow();
    this.createBuyWindow();
    this.createCategoryWindow();
    this.createSellWindow();
};

/* 创建金钱窗口 */
Scene_Shop.prototype.createGoldWindow = function() {
    this._goldWindow = new Window_Gold(0, this._helpWindow.height);
    this._goldWindow.x = Graphics.boxWidth - this._goldWindow.width;
    this.addWindow(this._goldWindow);
};

/* 创建指令窗口 */
Scene_Shop.prototype.createCommandWindow = function() {
    this._commandWindow = new Window_ShopCommand(this._goldWindow.x, this._purchaseOnly);
    this._commandWindow.y = this._helpWindow.height;
    this._commandWindow.setHandler('buy',    this.commandBuy.bind(this));
    this._commandWindow.setHandler('sell',   this.commandSell.bind(this));
    this._commandWindow.setHandler('cancel', this.popScene.bind(this));
    this.addWindow(this._commandWindow);
};

/* 创建样品窗口 */
Scene_Shop.prototype.createDummyWindow = function() {
    var wy = this._commandWindow.y + this._commandWindow.height;
    var wh = Graphics.boxHeight - wy;
    this._dummyWindow = new Window_Base(0, wy, Graphics.boxWidth, wh);
    this.addWindow(this._dummyWindow);
};

/* 创建数值窗口 */
Scene_Shop.prototype.createNumberWindow = function() {
    var wy = this._dummyWindow.y;
    var wh = this._dummyWindow.height;
    this._numberWindow = new Window_ShopNumber(0, wy, wh);
    this._numberWindow.hide();
    this._numberWindow.setHandler('ok',     this.onNumberOk.bind(this));
    this._numberWindow.setHandler('cancel', this.onNumberCancel.bind(this));
    this.addWindow(this._numberWindow);
};

/* 创建状态窗口 */
Scene_Shop.prototype.createStatusWindow = function() {
    var wx = this._numberWindow.width;
    var wy = this._dummyWindow.y;
    var ww = Graphics.boxWidth - wx;
    var wh = this._dummyWindow.height;
    this._statusWindow = new Window_ShopStatus(wx, wy, ww, wh);
    this._statusWindow.hide();
    this.addWindow(this._statusWindow);
};

/* 创建购买窗口 */
Scene_Shop.prototype.createBuyWindow = function() {
    var wy = this._dummyWindow.y;
    var wh = this._dummyWindow.height;
    this._buyWindow = new Window_ShopBuy(0, wy, wh, this._goods);
    this._buyWindow.setHelpWindow(this._helpWindow);
    this._buyWindow.setStatusWindow(this._statusWindow);
    this._buyWindow.hide();
    this._buyWindow.setHandler('ok',     this.onBuyOk.bind(this));
    this._buyWindow.setHandler('cancel', this.onBuyCancel.bind(this));
    this.addWindow(this._buyWindow);
};

/* 创建类型窗口 */
Scene_Shop.prototype.createCategoryWindow = function() {
    this._categoryWindow = new Window_ItemCategory();
    this._categoryWindow.setHelpWindow(this._helpWindow);
    this._categoryWindow.y = this._dummyWindow.y;
    this._categoryWindow.hide();
    this._categoryWindow.deactivate();
    this._categoryWindow.setHandler('ok',     this.onCategoryOk.bind(this));
    this._categoryWindow.setHandler('cancel', this.onCategoryCancel.bind(this));
    this.addWindow(this._categoryWindow);
};

/* 创建出售窗口 */
Scene_Shop.prototype.createSellWindow = function() {
    var wy = this._categoryWindow.y + this._categoryWindow.height;
    var wh = Graphics.boxHeight - wy;
    this._sellWindow = new Window_ShopSell(0, wy, Graphics.boxWidth, wh);
    this._sellWindow.setHelpWindow(this._helpWindow);
    this._sellWindow.hide();
    this._sellWindow.setHandler('ok',     this.onSellOk.bind(this));
    this._sellWindow.setHandler('cancel', this.onSellCancel.bind(this));
    this._categoryWindow.setItemWindow(this._sellWindow);
    this.addWindow(this._sellWindow);
};

/* 激活购买窗口 */
Scene_Shop.prototype.activateBuyWindow = function() {
    this._buyWindow.setMoney(this.money());
    this._buyWindow.show();
    this._buyWindow.activate();
    this._statusWindow.show();
};

/* 激活出售窗口 */
Scene_Shop.prototype.activateSellWindow = function() {
    this._categoryWindow.show();
    this._sellWindow.refresh();
    this._sellWindow.show();
    this._sellWindow.activate();
    this._statusWindow.hide();
};

/* 购买的指令 */
Scene_Shop.prototype.commandBuy = function() {
    this._dummyWindow.hide();
    this.activateBuyWindow();
};

/* 出售的指令 */
Scene_Shop.prototype.commandSell = function() {
    this._dummyWindow.hide();
    this._categoryWindow.show();
    this._categoryWindow.activate();
    this._sellWindow.show();
    this._sellWindow.deselect();
    this._sellWindow.refresh();
};

/* 当购买确定 */
Scene_Shop.prototype.onBuyOk = function() {
    this._item = this._buyWindow.item();
    this._buyWindow.hide();
    this._numberWindow.setup(this._item, this.maxBuy(), this.buyingPrice());
    this._numberWindow.setCurrencyUnit(this.currencyUnit());
    this._numberWindow.show();
    this._numberWindow.activate();
};

/* 当购买取消 */
Scene_Shop.prototype.onBuyCancel = function() {
    this._commandWindow.activate();
    this._dummyWindow.show();
    this._buyWindow.hide();
    this._statusWindow.hide();
    this._statusWindow.setItem(null);
    this._helpWindow.clear();
};

/* 当类型确定 */
Scene_Shop.prototype.onCategoryOk = function() {
    this.activateSellWindow();
    this._sellWindow.select(0);
};

/* 当类型取消 */
Scene_Shop.prototype.onCategoryCancel = function() {
    this._commandWindow.activate();
    this._dummyWindow.show();
    this._categoryWindow.hide();
    this._sellWindow.hide();
};

/* 当出售确定 */
Scene_Shop.prototype.onSellOk = function() {
    this._item = this._sellWindow.item();
    this._categoryWindow.hide();
    this._sellWindow.hide();
    this._numberWindow.setup(this._item, this.maxSell(), this.sellingPrice());
    this._numberWindow.setCurrencyUnit(this.currencyUnit());
    this._numberWindow.show();
    this._numberWindow.activate();
    this._statusWindow.setItem(this._item);
    this._statusWindow.show();
};

/* 当出售取消 */
Scene_Shop.prototype.onSellCancel = function() {
    this._sellWindow.deselect();
    this._categoryWindow.activate();
    this._statusWindow.setItem(null);
    this._helpWindow.clear();
};

/* 当数值确定 */
Scene_Shop.prototype.onNumberOk = function() {
    SoundManager.playShop();
    switch (this._commandWindow.currentSymbol()) {
    case 'buy':
        this.doBuy(this._numberWindow.number());
        break;
    case 'sell':
        this.doSell(this._numberWindow.number());
        break;
    }
    this.endNumberInput();
    this._goldWindow.refresh();
    this._statusWindow.refresh();
};

/* 当数值取消 */
Scene_Shop.prototype.onNumberCancel = function() {
    SoundManager.playCancel();
    this.endNumberInput();
};

/* 进行购买 */
Scene_Shop.prototype.doBuy = function(number) {
    $gameParty.loseGold(number * this.buyingPrice());
    $gameParty.gainItem(this._item, number);
};

/* 进行出售 */
Scene_Shop.prototype.doSell = function(number) {
    $gameParty.gainGold(number * this.sellingPrice());
    $gameParty.loseItem(this._item, number);
};

/* 结束数值输入 */
Scene_Shop.prototype.endNumberInput = function() {
    this._numberWindow.hide();
    switch (this._commandWindow.currentSymbol()) {
    case 'buy':
        this.activateBuyWindow();
        break;
    case 'sell':
        this.activateSellWindow();
        break;
    }
};

/* 最多购买数 */
Scene_Shop.prototype.maxBuy = function() {
    var max = $gameParty.maxItems(this._item) - $gameParty.numItems(this._item);
    var price = this.buyingPrice();
    if (price &gt; 0) {
        return Math.min(max, Math.floor(this.money() / price));
    } else {
        return max;
    }
};

/* 最多出售数 */
Scene_Shop.prototype.maxSell = function() {
    return $gameParty.numItems(this._item);
};

/* 金钱 */
Scene_Shop.prototype.money = function() {
    return this._goldWindow.value();
};

/* 货币单位 */
Scene_Shop.prototype.currencyUnit = function() {
    return this._goldWindow.currencyUnit();
};

/* 购买价格 */
Scene_Shop.prototype.buyingPrice = function() {
    return this._buyWindow.price(this._item);
};

/* 出售价格 */
Scene_Shop.prototype.sellingPrice = function() {
    return Math.floor(this._item.price / 2);
};

//-----------------------------------------------------------------------------
// 场景_名字 
// Scene_Name
//
// 名字输入画面的场景类。 
// The scene class of the name input screen.

function Scene_Name() {
    this.initialize.apply(this, arguments);
}

Scene_Name.prototype = Object.create(Scene_MenuBase.prototype);
Scene_Name.prototype.constructor = Scene_Name;

/* 初始化 */
Scene_Name.prototype.initialize = function() {
    Scene_MenuBase.prototype.initialize.call(this);
};

/* 准备 */
Scene_Name.prototype.prepare = function(actorId, maxLength) {
    this._actorId = actorId;
    this._maxLength = maxLength;
};

/* 创建 */
Scene_Name.prototype.create = function() {
    Scene_MenuBase.prototype.create.call(this);
    this._actor = $gameActors.actor(this._actorId);
    this.createEditWindow();
    this.createInputWindow();
};

/* 开始 */
Scene_Name.prototype.start = function() {
    Scene_MenuBase.prototype.start.call(this);
    this._editWindow.refresh();
};

/* 创建编辑窗口 */
Scene_Name.prototype.createEditWindow = function() {
    this._editWindow = new Window_NameEdit(this._actor, this._maxLength);
    this.addWindow(this._editWindow);
};

/* 创建输入窗口 */
Scene_Name.prototype.createInputWindow = function() {
    this._inputWindow = new Window_NameInput(this._editWindow);
    this._inputWindow.setHandler('ok', this.onInputOk.bind(this));
    this.addWindow(this._inputWindow);
};

/* 当输入确定 */
Scene_Name.prototype.onInputOk = function() {
    this._actor.setName(this._editWindow.name());
    this.popScene();
};

//-----------------------------------------------------------------------------
// 场景_调试 
// Scene_Debug
//
// 调试画面的场景类。 
// The scene class of the debug screen.

function Scene_Debug() {
    this.initialize.apply(this, arguments);
}

Scene_Debug.prototype = Object.create(Scene_MenuBase.prototype);
Scene_Debug.prototype.constructor = Scene_Debug;

/* 初始化 */
Scene_Debug.prototype.initialize = function() {
    Scene_MenuBase.prototype.initialize.call(this);
};

/* 创建 */
Scene_Debug.prototype.create = function() {
    Scene_MenuBase.prototype.create.call(this);
    this.createRangeWindow();
    this.createEditWindow();
    this.createDebugHelpWindow();
};

/* 创建范围窗口 */
Scene_Debug.prototype.createRangeWindow = function() {
    this._rangeWindow = new Window_DebugRange(0, 0);
    this._rangeWindow.setHandler('ok',     this.onRangeOk.bind(this));
    this._rangeWindow.setHandler('cancel', this.popScene.bind(this));
    this.addWindow(this._rangeWindow);
};

/* 创建编辑窗口 */
Scene_Debug.prototype.createEditWindow = function() {
    var wx = this._rangeWindow.width;
    var ww = Graphics.boxWidth - wx;
    this._editWindow = new Window_DebugEdit(wx, 0, ww);
    this._editWindow.setHandler('cancel', this.onEditCancel.bind(this));
    this._rangeWindow.setEditWindow(this._editWindow);
    this.addWindow(this._editWindow);
};

/* 创建调试帮助窗口 */
Scene_Debug.prototype.createDebugHelpWindow = function() {
    var wx = this._editWindow.x;
    var wy = this._editWindow.height;
    var ww = this._editWindow.width;
    var wh = Graphics.boxHeight - wy;
    this._debugHelpWindow = new Window_Base(wx, wy, ww, wh);
    this.addWindow(this._debugHelpWindow);
};

/* 当范围确定 */
Scene_Debug.prototype.onRangeOk = function() {
    this._editWindow.activate();
    this._editWindow.select(0);
    this.refreshHelpWindow();
};

/* 当编辑取消 */
Scene_Debug.prototype.onEditCancel = function() {
    this._rangeWindow.activate();
    this._editWindow.deselect();
    this.refreshHelpWindow();
};

/* 刷新帮助窗口 */
Scene_Debug.prototype.refreshHelpWindow = function() {
    this._debugHelpWindow.contents.clear();
    if (this._editWindow.active) {
        this._debugHelpWindow.drawTextEx(this.helpText(), 4, 0);
    }
};

/* 帮助文本 */
Scene_Debug.prototype.helpText = function() {
    if (this._rangeWindow.mode() === 'switch') {
        return 'Enter : ON / OFF';
    } else {
        return ('Left     :  -1\n' +
                'Right    :  +1\n' +
                'Pageup   : -10\n' +
                'Pagedown : +10');
    }
};

//-----------------------------------------------------------------------------
// 场景_战斗 
// Scene_Battle
//
// 战斗画面的场景类。 
// The scene class of the battle screen.

function Scene_Battle() {
    this.initialize.apply(this, arguments);
}

Scene_Battle.prototype = Object.create(Scene_Base.prototype);
Scene_Battle.prototype.constructor = Scene_Battle;

/* 初始化 */
Scene_Battle.prototype.initialize = function() {
    Scene_Base.prototype.initialize.call(this);
};

/* 创建 */
Scene_Battle.prototype.create = function() {
    Scene_Base.prototype.create.call(this);
    this.createDisplayObjects();
};

/* 开始 */
Scene_Battle.prototype.start = function() {
    Scene_Base.prototype.start.call(this);
    this.startFadeIn(this.fadeSpeed(), false);
    BattleManager.playBattleBgm();
    BattleManager.startBattle();
};

/* 更新 */
Scene_Battle.prototype.update = function() {
    var active = this.isActive();
    $gameTimer.update(active);
    $gameScreen.update();
    this.updateStatusWindow();
    this.updateWindowPositions();
    if (active &amp;&amp; !this.isBusy()) {
        this.updateBattleProcess();
    }
    Scene_Base.prototype.update.call(this);
};

/* 更新战斗流程 */
Scene_Battle.prototype.updateBattleProcess = function() {
    if (!this.isAnyInputWindowActive() || BattleManager.isAborting() ||
            BattleManager.isBattleEnd()) {
        BattleManager.update();
        this.changeInputWindow();
    }
};

/* 是否有任何输入窗口处于活动状态 */
Scene_Battle.prototype.isAnyInputWindowActive = function() {
    return (this._partyCommandWindow.active ||
            this._actorCommandWindow.active ||
            this._skillWindow.active ||
            this._itemWindow.active ||
            this._actorWindow.active ||
            this._enemyWindow.active);
};

/* 改变输入窗口 */
Scene_Battle.prototype.changeInputWindow = function() {
    if (BattleManager.isInputting()) {
        if (BattleManager.actor()) {
            this.startActorCommandSelection();
        } else {
            this.startPartyCommandSelection();
        }
    } else {
        this.endCommandSelection();
    }
};

/* 停止 */
Scene_Battle.prototype.stop = function() {
    Scene_Base.prototype.stop.call(this);
    if (this.needsSlowFadeOut()) {
        this.startFadeOut(this.slowFadeSpeed(), false);
    } else {
        this.startFadeOut(this.fadeSpeed(), false);
    }
    this._statusWindow.close();
    this._partyCommandWindow.close();
    this._actorCommandWindow.close();
};

/* 结束 */
Scene_Battle.prototype.terminate = function() {
    Scene_Base.prototype.terminate.call(this);
    $gameParty.onBattleEnd();
    $gameTroop.onBattleEnd();
    AudioManager.stopMe();

    ImageManager.clearRequest();
};

/* 是否需要缓慢淡出 */
Scene_Battle.prototype.needsSlowFadeOut = function() {
    return (SceneManager.isNextScene(Scene_Title) ||
            SceneManager.isNextScene(Scene_Gameover));
};

/* 更新状态窗口 */
Scene_Battle.prototype.updateStatusWindow = function() {
    if ($gameMessage.isBusy()) {
        this._statusWindow.close();
        this._partyCommandWindow.close();
        this._actorCommandWindow.close();
    } else if (this.isActive() &amp;&amp; !this._messageWindow.isClosing()) {
        this._statusWindow.open();
    }
};

/* 更新窗口位置 */
Scene_Battle.prototype.updateWindowPositions = function() {
    var statusX = 0;
    if (BattleManager.isInputting()) {
        statusX = this._partyCommandWindow.width;
    } else {
        statusX = this._partyCommandWindow.width / 2;
    }
    if (this._statusWindow.x &lt; statusX) {
        this._statusWindow.x += 16;
        if (this._statusWindow.x &gt; statusX) {
            this._statusWindow.x = statusX;
        }
    }
    if (this._statusWindow.x &gt; statusX) {
        this._statusWindow.x -= 16;
        if (this._statusWindow.x &lt; statusX) {
            this._statusWindow.x = statusX;
        }
    }
};

/* 创建显示对象 */
Scene_Battle.prototype.createDisplayObjects = function() {
    this.createSpriteset();
    this.createWindowLayer();
    this.createAllWindows();
    BattleManager.setLogWindow(this._logWindow);
    BattleManager.setStatusWindow(this._statusWindow);
    BattleManager.setSpriteset(this._spriteset);
    this._logWindow.setSpriteset(this._spriteset);
};

/* 创建精灵组 */
Scene_Battle.prototype.createSpriteset = function() {
    this._spriteset = new Spriteset_Battle();
    this.addChild(this._spriteset);
};

/* 创建所有窗口 */
Scene_Battle.prototype.createAllWindows = function() {
    this.createLogWindow();
    this.createStatusWindow();
    this.createPartyCommandWindow();
    this.createActorCommandWindow();
    this.createHelpWindow();
    this.createSkillWindow();
    this.createItemWindow();
    this.createActorWindow();
    this.createEnemyWindow();
    this.createMessageWindow();
    this.createScrollTextWindow();
};

/* 创建日志窗口 */
Scene_Battle.prototype.createLogWindow = function() {
    this._logWindow = new Window_BattleLog();
    this.addWindow(this._logWindow);
};

/* 创建状态窗口 */
Scene_Battle.prototype.createStatusWindow = function() {
    this._statusWindow = new Window_BattleStatus();
    this.addWindow(this._statusWindow);
};

/* 创建队伍指令窗口 */
Scene_Battle.prototype.createPartyCommandWindow = function() {
    this._partyCommandWindow = new Window_PartyCommand();
    this._partyCommandWindow.setHandler('fight',  this.commandFight.bind(this));
    this._partyCommandWindow.setHandler('escape', this.commandEscape.bind(this));
    this._partyCommandWindow.deselect();
    this.addWindow(this._partyCommandWindow);
};

/* 创建角色指令窗口 */
Scene_Battle.prototype.createActorCommandWindow = function() {
    this._actorCommandWindow = new Window_ActorCommand();
    this._actorCommandWindow.setHandler('attack', this.commandAttack.bind(this));
    this._actorCommandWindow.setHandler('skill',  this.commandSkill.bind(this));
    this._actorCommandWindow.setHandler('guard',  this.commandGuard.bind(this));
    this._actorCommandWindow.setHandler('item',   this.commandItem.bind(this));
    this._actorCommandWindow.setHandler('cancel', this.selectPreviousCommand.bind(this));
    this.addWindow(this._actorCommandWindow);
};

/* 创建帮助窗口 */
Scene_Battle.prototype.createHelpWindow = function() {
    this._helpWindow = new Window_Help();
    this._helpWindow.visible = false;
    this.addWindow(this._helpWindow);
};

/* 创建技能窗口 */
Scene_Battle.prototype.createSkillWindow = function() {
    var wy = this._helpWindow.y + this._helpWindow.height;
    var wh = this._statusWindow.y - wy;
    this._skillWindow = new Window_BattleSkill(0, wy, Graphics.boxWidth, wh);
    this._skillWindow.setHelpWindow(this._helpWindow);
    this._skillWindow.setHandler('ok',     this.onSkillOk.bind(this));
    this._skillWindow.setHandler('cancel', this.onSkillCancel.bind(this));
    this.addWindow(this._skillWindow);
};

/* 创建物品窗口 */
Scene_Battle.prototype.createItemWindow = function() {
    var wy = this._helpWindow.y + this._helpWindow.height;
    var wh = this._statusWindow.y - wy;
    this._itemWindow = new Window_BattleItem(0, wy, Graphics.boxWidth, wh);
    this._itemWindow.setHelpWindow(this._helpWindow);
    this._itemWindow.setHandler('ok',     this.onItemOk.bind(this));
    this._itemWindow.setHandler('cancel', this.onItemCancel.bind(this));
    this.addWindow(this._itemWindow);
};

/* 创建角色窗口 */
Scene_Battle.prototype.createActorWindow = function() {
    this._actorWindow = new Window_BattleActor(0, this._statusWindow.y);
    this._actorWindow.setHandler('ok',     this.onActorOk.bind(this));
    this._actorWindow.setHandler('cancel', this.onActorCancel.bind(this));
    this.addWindow(this._actorWindow);
};

/* 创建敌人窗口 */
Scene_Battle.prototype.createEnemyWindow = function() {
    this._enemyWindow = new Window_BattleEnemy(0, this._statusWindow.y);
    this._enemyWindow.x = Graphics.boxWidth - this._enemyWindow.width;
    this._enemyWindow.setHandler('ok',     this.onEnemyOk.bind(this));
    this._enemyWindow.setHandler('cancel', this.onEnemyCancel.bind(this));
    this.addWindow(this._enemyWindow);
};

/* 创建信息窗口 */
Scene_Battle.prototype.createMessageWindow = function() {
    this._messageWindow = new Window_Message();
    this.addWindow(this._messageWindow);
    this._messageWindow.subWindows().forEach(function(window) {
        this.addWindow(window);
    }, this);
};

/* 创建滚动文本窗口 */
Scene_Battle.prototype.createScrollTextWindow = function() {
    this._scrollTextWindow = new Window_ScrollText();
    this.addWindow(this._scrollTextWindow);
};

/* 刷新状态 */
Scene_Battle.prototype.refreshStatus = function() {
    this._statusWindow.refresh();
};

/* 开始队伍指令选择 */
Scene_Battle.prototype.startPartyCommandSelection = function() {
    this.refreshStatus();
    this._statusWindow.deselect();
    this._statusWindow.open();
    this._actorCommandWindow.close();
    this._partyCommandWindow.setup();
};

/* 战斗的指令 */
Scene_Battle.prototype.commandFight = function() {
    this.selectNextCommand();
};

/* 逃跑的指令 */
Scene_Battle.prototype.commandEscape = function() {
    BattleManager.processEscape();
    this.changeInputWindow();
};

/* 开始角色指令选择 */
Scene_Battle.prototype.startActorCommandSelection = function() {
    this._statusWindow.select(BattleManager.actor().index());
    this._partyCommandWindow.close();
    this._actorCommandWindow.setup(BattleManager.actor());
};

/* 攻击的指令 */
Scene_Battle.prototype.commandAttack = function() {
    BattleManager.inputtingAction().setAttack();
    this.selectEnemySelection();
};

/* 技能的指令 */
Scene_Battle.prototype.commandSkill = function() {
    this._skillWindow.setActor(BattleManager.actor());
    this._skillWindow.setStypeId(this._actorCommandWindow.currentExt());
    this._skillWindow.refresh();
    this._skillWindow.show();
    this._skillWindow.activate();
};

/* 防御的指令 */
Scene_Battle.prototype.commandGuard = function() {
    BattleManager.inputtingAction().setGuard();
    this.selectNextCommand();
};

/* 物品的指令 */
Scene_Battle.prototype.commandItem = function() {
    this._itemWindow.refresh();
    this._itemWindow.show();
    this._itemWindow.activate();
};

/* 选择下一个指令 */
Scene_Battle.prototype.selectNextCommand = function() {
    BattleManager.selectNextCommand();
    this.changeInputWindow();
};

/* 选择上一个指令 */
Scene_Battle.prototype.selectPreviousCommand = function() {
    BattleManager.selectPreviousCommand();
    this.changeInputWindow();
};

/* 选择可选择的角色 */
Scene_Battle.prototype.selectActorSelection = function() {
    this._actorWindow.refresh();
    this._actorWindow.show();
    this._actorWindow.activate();
};

/* 当角色确定 */
Scene_Battle.prototype.onActorOk = function() {
    var action = BattleManager.inputtingAction();
    action.setTarget(this._actorWindow.index());
    this._actorWindow.hide();
    this._skillWindow.hide();
    this._itemWindow.hide();
    this.selectNextCommand();
};

/* 当角色取消 */
Scene_Battle.prototype.onActorCancel = function() {
    this._actorWindow.hide();
    switch (this._actorCommandWindow.currentSymbol()) {
    case 'skill':
        this._skillWindow.show();
        this._skillWindow.activate();
        break;
    case 'item':
        this._itemWindow.show();
        this._itemWindow.activate();
        break;
    }
};

/* 选择可选择的敌人 */
Scene_Battle.prototype.selectEnemySelection = function() {
    this._enemyWindow.refresh();
    this._enemyWindow.show();
    this._enemyWindow.select(0);
    this._enemyWindow.activate();
};

/* 当敌人确定 */
Scene_Battle.prototype.onEnemyOk = function() {
    var action = BattleManager.inputtingAction();
    action.setTarget(this._enemyWindow.enemyIndex());
    this._enemyWindow.hide();
    this._skillWindow.hide();
    this._itemWindow.hide();
    this.selectNextCommand();
};

/* 当敌人取消 */
Scene_Battle.prototype.onEnemyCancel = function() {
    this._enemyWindow.hide();
    switch (this._actorCommandWindow.currentSymbol()) {
    case 'attack':
        this._actorCommandWindow.activate();
        break;
    case 'skill':
        this._skillWindow.show();
        this._skillWindow.activate();
        break;
    case 'item':
        this._itemWindow.show();
        this._itemWindow.activate();
        break;
    }
};

/* 当技能确定 */
Scene_Battle.prototype.onSkillOk = function() {
    var skill = this._skillWindow.item();
    var action = BattleManager.inputtingAction();
    action.setSkill(skill.id);
    BattleManager.actor().setLastBattleSkill(skill);
    this.onSelectAction();
};

/* 当技能取消 */
Scene_Battle.prototype.onSkillCancel = function() {
    this._skillWindow.hide();
    this._actorCommandWindow.activate();
};

/* 当物品确定 */
Scene_Battle.prototype.onItemOk = function() {
    var item = this._itemWindow.item();
    var action = BattleManager.inputtingAction();
    action.setItem(item.id);
    $gameParty.setLastItem(item);
    this.onSelectAction();
};

/* 当物品取消 */
Scene_Battle.prototype.onItemCancel = function() {
    this._itemWindow.hide();
    this._actorCommandWindow.activate();
};

/* 当选择行动 */
Scene_Battle.prototype.onSelectAction = function() {
    var action = BattleManager.inputtingAction();
    this._skillWindow.hide();
    this._itemWindow.hide();
    if (!action.needsSelection()) {
        this.selectNextCommand();
    } else if (action.isForOpponent()) {
        this.selectEnemySelection();
    } else {
        this.selectActorSelection();
    }
};

/* 结束指令选择 */
Scene_Battle.prototype.endCommandSelection = function() {
    this._partyCommandWindow.close();
    this._actorCommandWindow.close();
    this._statusWindow.deselect();
};

//-----------------------------------------------------------------------------
// 场景_游戏结束 
// Scene_Gameover
//
// 游戏结束画面的场景类。 
// The scene class of the game over screen.

function Scene_Gameover() {
    this.initialize.apply(this, arguments);
}

Scene_Gameover.prototype = Object.create(Scene_Base.prototype);
Scene_Gameover.prototype.constructor = Scene_Gameover;

/* 初始化 */
Scene_Gameover.prototype.initialize = function() {
    Scene_Base.prototype.initialize.call(this);
};

/* 创建 */
Scene_Gameover.prototype.create = function() {
    Scene_Base.prototype.create.call(this);
    this.playGameoverMusic();
    this.createBackground();
};

/* 开始 */
Scene_Gameover.prototype.start = function() {
    Scene_Base.prototype.start.call(this);
    this.startFadeIn(this.slowFadeSpeed(), false);
};

/* 更新 */
Scene_Gameover.prototype.update = function() {
    if (this.isActive() &amp;&amp; !this.isBusy() &amp;&amp; this.isTriggered()) {
        this.gotoTitle();
    }
    Scene_Base.prototype.update.call(this);
};

/* 停止 */
Scene_Gameover.prototype.stop = function() {
    Scene_Base.prototype.stop.call(this);
    this.fadeOutAll();
};

/* 结束 */
Scene_Gameover.prototype.terminate = function() {
    Scene_Base.prototype.terminate.call(this);
    AudioManager.stopAll();
};

/* 播放游戏结束音乐 */
Scene_Gameover.prototype.playGameoverMusic = function() {
    AudioManager.stopBgm();
    AudioManager.stopBgs();
    AudioManager.playMe($dataSystem.gameoverMe);
};

/* 创建背景 */
Scene_Gameover.prototype.createBackground = function() {
    this._backSprite = new Sprite();
    this._backSprite.bitmap = ImageManager.loadSystem('GameOver');
    this.addChild(this._backSprite);
};

/* 是否触发 */
Scene_Gameover.prototype.isTriggered = function() {
    return Input.isTriggered('ok') || TouchInput.isTriggered();
};

/* 回到标题 */ 
Scene_Gameover.prototype.gotoTitle = function() {
    SceneManager.goto(Scene_Title);
};</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_精灵_rpg_sprites_js">精灵: rpg_sprites.js</h2>
<div class="sectionbody">
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Sprite_Base: 精灵_基础</p>
</li>
<li>
<p>Sprite_Button: 精灵_按钮</p>
</li>
<li>
<p>Sprite_Character: 精灵_人物</p>
</li>
<li>
<p>Sprite_Battler: 精灵_战斗者</p>
</li>
<li>
<p>Sprite_Actor: 精灵_角色</p>
</li>
<li>
<p>Sprite_Enemy: 精灵_敌人</p>
</li>
<li>
<p>Sprite_Animation: 精灵_动画</p>
</li>
<li>
<p>Sprite_Damage: 精灵_伤害</p>
</li>
<li>
<p>Sprite_StateIcon: 精灵_状态图标</p>
</li>
<li>
<p>Sprite_StateOverlay: 精灵_状态覆盖</p>
</li>
<li>
<p>Sprite_Weapon: 精灵_武器</p>
</li>
<li>
<p>Sprite_Balloon: 精灵_气泡</p>
</li>
<li>
<p>Sprite_Picture: 精灵_图片</p>
</li>
<li>
<p>Sprite_Timer: 精灵_计时器</p>
</li>
<li>
<p>Sprite_Destination: 精灵_目的地</p>
</li>
<li>
<p>Spriteset_Base: 精灵组_基础</p>
</li>
<li>
<p>Spriteset_Map: 精灵组_地图</p>
</li>
<li>
<p>Spriteset_Battle: 精灵组_战斗</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-javascript" data-lang="javascript">//=============================================================================
// rpg_sprites.js v1.6.1
//=============================================================================

//-----------------------------------------------------------------------------
// 精灵_基础 
// Sprite_Base
//
// 具有显示动画功能的精灵类。 
// The sprite class with a feature which displays animations.

function Sprite_Base() {
    this.initialize.apply(this, arguments);
}

Sprite_Base.prototype = Object.create(Sprite.prototype);
Sprite_Base.prototype.constructor = Sprite_Base;

/* 初始化 */
Sprite_Base.prototype.initialize = function() {
    Sprite.prototype.initialize.call(this);
    this._animationSprites = [];
    this._effectTarget = this;
    this._hiding = false;
};

/* 更新 */
Sprite_Base.prototype.update = function() {
    Sprite.prototype.update.call(this);
    this.updateVisibility();
    this.updateAnimationSprites();
};

/* 隐藏 */
Sprite_Base.prototype.hide = function() {
    this._hiding = true;
    this.updateVisibility();
};

/* 显示 */
Sprite_Base.prototype.show = function() {
    this._hiding = false;
    this.updateVisibility();
};

/* 更新可见性 */
Sprite_Base.prototype.updateVisibility = function() {
    this.visible = !this._hiding;
};

/* 更新动画精灵 */
Sprite_Base.prototype.updateAnimationSprites = function() {
    if (this._animationSprites.length &gt; 0) {
        var sprites = this._animationSprites.clone();
        this._animationSprites = [];
        for (var i = 0; i &lt; sprites.length; i) {
            var sprite = sprites[i];
            if (sprite.isPlaying()) {
                this._animationSprites.push(sprite);
            } else {
                sprite.remove();
            }
        }
    }
};

/* 开始动画 */
Sprite_Base.prototype.startAnimation = function(animation, mirror, delay) {
    var sprite = new Sprite_Animation();
    sprite.setup(this._effectTarget, animation, mirror, delay);
    this.parent.addChild(sprite);
    this._animationSprites.push(sprite);
};

/* 是否动画播放中 */
Sprite_Base.prototype.isAnimationPlaying = function() {
    return this._animationSprites.length &gt; 0;
};

//-----------------------------------------------------------------------------
// 精灵_按钮 
// Sprite_Button
//
// 显示按钮的精灵。 
// The sprite for displaying a button.

function Sprite_Button() {
    this.initialize.apply(this, arguments);
}

Sprite_Button.prototype = Object.create(Sprite.prototype);
Sprite_Button.prototype.constructor = Sprite_Button;

/* 初始化 */
Sprite_Button.prototype.initialize = function() {
    Sprite.prototype.initialize.call(this);
    this._touching = false;
    this._coldFrame = null;
    this._hotFrame = null;
    this._clickHandler = null;
};

/* 更新 */
Sprite_Button.prototype.update = function() {
    Sprite.prototype.update.call(this);
    this.updateFrame();
    this.processTouch();
};

/* 更新帧 */
Sprite_Button.prototype.updateFrame = function() {
    var frame;
    if (this._touching) {
        frame = this._hotFrame;
    } else {
        frame = this._coldFrame;
    }
    if (frame) {
        this.setFrame(frame.x, frame.y, frame.width, frame.height);
    }
};

/* 设置冷帧 
 * 按钮未按下时的显示区域。 
 */
Sprite_Button.prototype.setColdFrame = function(x, y, width, height) {
    this._coldFrame = new Rectangle(x, y, width, height);
};

/* 设置热帧 
 * 按钮按下时的显示区域。 
 */
Sprite_Button.prototype.setHotFrame = function(x, y, width, height) {
    this._hotFrame = new Rectangle(x, y, width, height);
};

/* 设置点击处理者 */
Sprite_Button.prototype.setClickHandler = function(method) {
    this._clickHandler = method;
};

/* 呼叫点击处理者 */
Sprite_Button.prototype.callClickHandler = function() {
    if (this._clickHandler) {
        this._clickHandler();
    }
};

/* 处理触摸 */
Sprite_Button.prototype.processTouch = function() {
    if (this.isActive()) {
        if (TouchInput.isTriggered() &amp;&amp; this.isButtonTouched()) {
            this._touching = true;
        }
        if (this._touching) {
            if (TouchInput.isReleased() || !this.isButtonTouched()) {
                this._touching = false;
                if (TouchInput.isReleased()) {
                    this.callClickHandler();
                }
            }
        }
    } else {
        this._touching = false;
    }
};

/* 是否活动的 */
Sprite_Button.prototype.isActive = function() {
    var node = this;
    while (node) {
        if (!node.visible) {
            return false;
        }
        node = node.parent;
    }
    return true;
};

/* 是否按钮被触摸 */
Sprite_Button.prototype.isButtonTouched = function() {
    var x = this.canvasToLocalX(TouchInput.x);
    var y = this.canvasToLocalY(TouchInput.y);
    return x &gt;= 0 &amp;&amp; y &gt;= 0 &amp;&amp; x &lt; this.width &amp;&amp; y &lt; this.height;
};

/* 画布 X 坐标转换到本地 X 坐标 */
Sprite_Button.prototype.canvasToLocalX = function(x) {
    var node = this;
    while (node) {
        x -= node.x;
        node = node.parent;
    }
    return x;
};

/* 画布 Y 坐标转换到本地 Y 坐标 */
Sprite_Button.prototype.canvasToLocalY = function(y) {
    var node = this;
    while (node) {
        y -= node.y;
        node = node.parent;
    }
    return y;
};

//-----------------------------------------------------------------------------
// 精灵_人物 
// Sprite_Character
//
// 显示角色的精灵。 
// The sprite for displaying a character.

function Sprite_Character() {
    this.initialize.apply(this, arguments);
}

Sprite_Character.prototype = Object.create(Sprite_Base.prototype);
Sprite_Character.prototype.constructor = Sprite_Character;

/* 初始化 */
Sprite_Character.prototype.initialize = function(character) {
    Sprite_Base.prototype.initialize.call(this);
    this.initMembers();
    this.setCharacter(character);
};

/* 初始化成员 */
Sprite_Character.prototype.initMembers = function() {
    this.anchor.x = 0.5;
    this.anchor.y = 1;
    this._character = null;
    this._balloonDuration = 0;
    this._tilesetId = 0;
    this._upperBody = null;
    this._lowerBody = null;
};

/* 设置人物 */
Sprite_Character.prototype.setCharacter = function(character) {
    this._character = character;
};

/* 更新 */
Sprite_Character.prototype.update = function() {
    Sprite_Base.prototype.update.call(this);
    this.updateBitmap();
    this.updateFrame();
    this.updatePosition();
    this.updateAnimation();
    this.updateBalloon();
    this.updateOther();
};

/* 更新可见性 */
Sprite_Character.prototype.updateVisibility = function() {
    Sprite_Base.prototype.updateVisibility.call(this);
    if (this._character.isTransparent()) {
        this.visible = false;
    }
};

/* 是否图块 */
Sprite_Character.prototype.isTile = function() {
    return this._character.tileId &gt; 0;
};

/* 图块组位图 */
Sprite_Character.prototype.tilesetBitmap = function(tileId) {
    var tileset = $gameMap.tileset();
    var setNumber = 5 + Math.floor(tileId / 256);
    return ImageManager.loadTileset(tileset.tilesetNames[setNumber]);
};

/* 更新位图 */
Sprite_Character.prototype.updateBitmap = function() {
    if (this.isImageChanged()) {
        this._tilesetId = $gameMap.tilesetId();
        this._tileId = this._character.tileId();
        this._characterName = this._character.characterName();
        this._characterIndex = this._character.characterIndex();
        if (this._tileId &gt; 0) {
            this.setTileBitmap();
        } else {
            this.setCharacterBitmap();
        }
    }
};

/* 是否图像改变 */
Sprite_Character.prototype.isImageChanged = function() {
    return (this._tilesetId !== $gameMap.tilesetId() ||
            this._tileId !== this._character.tileId() ||
            this._characterName !== this._character.characterName() ||
            this._characterIndex !== this._character.characterIndex());
};

/* 设置图块位图 */
Sprite_Character.prototype.setTileBitmap = function() {
    this.bitmap = this.tilesetBitmap(this._tileId);
};

/* 设置人物位图 */
Sprite_Character.prototype.setCharacterBitmap = function() {
    this.bitmap = ImageManager.loadCharacter(this._characterName);
    this._isBigCharacter = ImageManager.isBigCharacter(this._characterName);
};

/* 更新帧 */
Sprite_Character.prototype.updateFrame = function() {
    if (this._tileId &gt; 0) {
        this.updateTileFrame();
    } else {
        this.updateCharacterFrame();
    }
};

/* 更新图块帧 */
Sprite_Character.prototype.updateTileFrame = function() {
    var pw = this.patternWidth();
    var ph = this.patternHeight();
    var sx = (Math.floor(this._tileId / 128) % 2 * 8 + this._tileId % 8) * pw;
    var sy = Math.floor(this._tileId % 256 / 8) % 16 * ph;
    this.setFrame(sx, sy, pw, ph);
};

/* 更新行走图帧 */
Sprite_Character.prototype.updateCharacterFrame = function() {
    var pw = this.patternWidth();
    var ph = this.patternHeight();
    var sx = (this.characterBlockX() + this.characterPatternX()) * pw;
    var sy = (this.characterBlockY() + this.characterPatternY()) * ph;
    this.updateHalfBodySprites();
    if (this._bushDepth &gt; 0) {
        var d = this._bushDepth;
        this._upperBody.setFrame(sx, sy, pw, ph - d);
        this._lowerBody.setFrame(sx, sy + ph - d, pw, d);
        this.setFrame(sx, sy, 0, ph);
    } else {
        this.setFrame(sx, sy, pw, ph);
    }
};

/* 行走图块位置 X */
Sprite_Character.prototype.characterBlockX = function() {
    if (this._isBigCharacter) {
        return 0;
    } else {
        var index = this._character.characterIndex();
        return index % 4 * 3;
    }
};

/* 行走图块位置 Y */
Sprite_Character.prototype.characterBlockY = function() {
    if (this._isBigCharacter) {
        return 0;
    } else {
        var index = this._character.characterIndex();
        return Math.floor(index / 4) * 4;
    }
};

/* 行走图图案位置 X */
Sprite_Character.prototype.characterPatternX = function() {
    return this._character.pattern();
};

/* 行走图图案位置 Y */
Sprite_Character.prototype.characterPatternY = function() {
    return (this._character.direction() - 2) / 2;
};

/* 图案宽度 */
Sprite_Character.prototype.patternWidth = function() {
    if (this._tileId &gt; 0) {
        return $gameMap.tileWidth();
    } else if (this._isBigCharacter) {
        return this.bitmap.width / 3;
    } else {
        return this.bitmap.width / 12;
    }
};

/* 图案高度 */
Sprite_Character.prototype.patternHeight = function() {
    if (this._tileId &gt; 0) {
        return $gameMap.tileHeight();
    } else if (this._isBigCharacter) {
        return this.bitmap.height / 4;
    } else {
        return this.bitmap.height / 8;
    }
};

/* 更新半身精灵 */
Sprite_Character.prototype.updateHalfBodySprites = function() {
    if (this._bushDepth &gt; 0) {
        this.createHalfBodySprites();
        this._upperBody.bitmap = this.bitmap;
        this._upperBody.visible = true;
        this._upperBody.y = - this._bushDepth;
        this._lowerBody.bitmap = this.bitmap;
        this._lowerBody.visible = true;
        this._upperBody.setBlendColor(this.getBlendColor());
        this._lowerBody.setBlendColor(this.getBlendColor());
        this._upperBody.setColorTone(this.getColorTone());
        this._lowerBody.setColorTone(this.getColorTone());
    } else if (this._upperBody) {
        this._upperBody.visible = false;
        this._lowerBody.visible = false;
    }
};

/* 创建半身精灵 */
Sprite_Character.prototype.createHalfBodySprites = function() {
    if (!this._upperBody) {
        this._upperBody = new Sprite();
        this._upperBody.anchor.x = 0.5;
        this._upperBody.anchor.y = 1;
        this.addChild(this._upperBody);
    }
    if (!this._lowerBody) {
        this._lowerBody = new Sprite();
        this._lowerBody.anchor.x = 0.5;
        this._lowerBody.anchor.y = 1;
        this._lowerBody.opacity = 128;
        this.addChild(this._lowerBody);
    }
};

/* 更新位置 */
Sprite_Character.prototype.updatePosition = function() {
    this.x = this._character.screenX();
    this.y = this._character.screenY();
    this.z = this._character.screenZ();
};

/* 更新动画 */
Sprite_Character.prototype.updateAnimation = function() {
    this.setupAnimation();
    if (!this.isAnimationPlaying()) {
        this._character.endAnimation();
    }
    if (!this.isBalloonPlaying()) {
        this._character.endBalloon();
    }
};

/* 更新其它 */
Sprite_Character.prototype.updateOther = function() {
    this.opacity = this._character.opacity();
    this.blendMode = this._character.blendMode();
    this._bushDepth = this._character.bushDepth();
};

/* 设置动画 */
Sprite_Character.prototype.setupAnimation = function() {
    if (this._character.animationId() &gt; 0) {
        var animation = $dataAnimations[this._character.animationId()];
        this.startAnimation(animation, false, 0);
        this._character.startAnimation();
    }
};

/* 设置气泡图标 */
Sprite_Character.prototype.setupBalloon = function() {
    if (this._character.balloonId() &gt; 0) {
        this.startBalloon();
        this._character.startBalloon();
    }
};

/* 开始气泡图标 */
Sprite_Character.prototype.startBalloon = function() {
    if (!this._balloonSprite) {
        this._balloonSprite = new Sprite_Balloon();
    }
    this._balloonSprite.setup(this._character.balloonId());
    this.parent.addChild(this._balloonSprite);
};

/* 更新气泡图标 */
Sprite_Character.prototype.updateBalloon = function() {
    this.setupBalloon();
    if (this._balloonSprite) {
        this._balloonSprite.x = this.x;
        this._balloonSprite.y = this.y - this.height;
        if (!this._balloonSprite.isPlaying()) {
            this.endBalloon();
        }
    }
};

/* 结束气泡图标 */
Sprite_Character.prototype.endBalloon = function() {
    if (this._balloonSprite) {
        this.parent.removeChild(this._balloonSprite);
        this._balloonSprite = null;
    }
};

/* 是否气泡图标播放中 */
Sprite_Character.prototype.isBalloonPlaying = function() {
    return !!this._balloonSprite;
};

//-----------------------------------------------------------------------------
// 精灵_战斗者 
// Sprite_Battler
//
// Sprite_Actor 和 Sprite_Enemy 的父类。 
// The superclass of Sprite_Actor and Sprite_Enemy.

function Sprite_Battler() {
    this.initialize.apply(this, arguments);
}

Sprite_Battler.prototype = Object.create(Sprite_Base.prototype);
Sprite_Battler.prototype.constructor = Sprite_Battler;

/* 初始化 */
Sprite_Battler.prototype.initialize = function(battler) {
    Sprite_Base.prototype.initialize.call(this);
    this.initMembers();
    this.setBattler(battler);
};

/* 初始化成员 */
Sprite_Battler.prototype.initMembers = function() {
    this.anchor.x = 0.5;
    this.anchor.y = 1;
    this._battler = null;
    this._damages = [];
    this._homeX = 0;
    this._homeY = 0;
    this._offsetX = 0;
    this._offsetY = 0;
    this._targetOffsetX = NaN;
    this._targetOffsetY = NaN;
    this._movementDuration = 0;
    this._selectionEffectCount = 0;
};

/* 设置战斗者 */
Sprite_Battler.prototype.setBattler = function(battler) {
    this._battler = battler;
};

/* 设置家 
 * 以该位置为原点来设置战斗者的偏移位置。 
 */
Sprite_Battler.prototype.setHome = function(x, y) {
    this._homeX = x;
    this._homeY = y;
    this.updatePosition();
};

/* 更新 */
Sprite_Battler.prototype.update = function() {
    Sprite_Base.prototype.update.call(this);
    if (this._battler) {
        this.updateMain();
        this.updateAnimation();
        this.updateDamagePopup();
        this.updateSelectionEffect();
    } else {
        this.bitmap = null;
    }
};

/* 更新可见性 */
Sprite_Battler.prototype.updateVisibility = function() {
    Sprite_Base.prototype.updateVisibility.call(this);
    if (!this._battler || !this._battler.isSpriteVisible()) {
        this.visible = false;
    }
};

/* 更新主函数 */
Sprite_Battler.prototype.updateMain = function() {
    if (this._battler.isSpriteVisible()) {
        this.updateBitmap();
        this.updateFrame();
    }
    this.updateMove();
    this.updatePosition();
};

/* 更新位图 */
Sprite_Battler.prototype.updateBitmap = function() {
};

/* 更新帧 */
Sprite_Battler.prototype.updateFrame = function() {
};

/* 更新移动 */
Sprite_Battler.prototype.updateMove = function() {
    if (this._movementDuration &gt; 0) {
        var d = this._movementDuration;
        this._offsetX = (this._offsetX * (d - 1) + this._targetOffsetX) / d;
        this._offsetY = (this._offsetY * (d - 1) + this._targetOffsetY) / d;
        this._movementDuration--;
        if (this._movementDuration === 0) {
            this.onMoveEnd();
        }
    }
};

/* 更新位置 */
Sprite_Battler.prototype.updatePosition = function() {
    this.x = this._homeX + this._offsetX;
    this.y = this._homeY + this._offsetY;
};

/* 更新动画 */
Sprite_Battler.prototype.updateAnimation = function() {
    this.setupAnimation();
};

/* 更新伤害弹出层 */
Sprite_Battler.prototype.updateDamagePopup = function() {
    this.setupDamagePopup();
    if (this._damages.length &gt; 0) {
        for (var i = 0; i &lt; this._damages.length; i) {
            this._damages[i].update();
        }
        if (!this._damages[0].isPlaying()) {
            this.parent.removeChild(this._damages[0]);
            this._damages.shift();
        }
    }
};

/* 更新选择效果 */
Sprite_Battler.prototype.updateSelectionEffect = function() {
    var target = this._effectTarget;
    if (this._battler.isSelected()) {
        this._selectionEffectCount;
        if (this._selectionEffectCount % 30 &lt; 15) {
            target.setBlendColor([255, 255, 255, 64]);
        } else {
            target.setBlendColor([0, 0, 0, 0]);
        }
    } else if (this._selectionEffectCount &gt; 0) {
        this._selectionEffectCount = 0;
        target.setBlendColor([0, 0, 0, 0]);
    }
};

/* 设置动画 */
Sprite_Battler.prototype.setupAnimation = function() {
    while (this._battler.isAnimationRequested()) {
        var data = this._battler.shiftAnimation();
        var animation = $dataAnimations[data.animationId];
        var mirror = data.mirror;
        var delay = animation.position === 3 ? 0 : data.delay;
        this.startAnimation(animation, mirror, delay);
        for (var i = 0; i &lt; this._animationSprites.length; i) {
            var sprite = this._animationSprites[i];
            sprite.visible = this._battler.isSpriteVisible();
        }
    }
};

/* 设置伤害弹出层 */
Sprite_Battler.prototype.setupDamagePopup = function() {
    if (this._battler.isDamagePopupRequested()) {
        if (this._battler.isSpriteVisible()) {
            var sprite = new Sprite_Damage();
            sprite.x = this.x + this.damageOffsetX();
            sprite.y = this.y + this.damageOffsetY();
            sprite.setup(this._battler);
            this._damages.push(sprite);
            this.parent.addChild(sprite);
        }
        this._battler.clearDamagePopup();
        this._battler.clearResult();
    }
};

/* 伤害的偏移坐标 X */
Sprite_Battler.prototype.damageOffsetX = function() {
    return 0;
};

/* 伤害的偏移坐标 Y */
Sprite_Battler.prototype.damageOffsetY = function() {
    return 0;
};

/* 开始移动 */
Sprite_Battler.prototype.startMove = function(x, y, duration) {
    if (this._targetOffsetX !== x || this._targetOffsetY !== y) {
        this._targetOffsetX = x;
        this._targetOffsetY = y;
        this._movementDuration = duration;
        if (duration === 0) {
            this._offsetX = x;
            this._offsetY = y;
        }
    }
};

/* 当移动结束 */
Sprite_Battler.prototype.onMoveEnd = function() {
};

/* 是否效果中 */
Sprite_Battler.prototype.isEffecting = function() {
    return false;
};

/* 是否移动中 */
Sprite_Battler.prototype.isMoving = function() {
    return this._movementDuration &gt; 0;
};

/* 是否在家的坐标中 */
Sprite_Battler.prototype.inHomePosition = function() {
    return this._offsetX === 0 &amp;&amp; this._offsetY === 0;
};

//-----------------------------------------------------------------------------
// 精灵_角色 
// Sprite_Actor
//
// 显示角色的精灵。 
// The sprite for displaying an actor.

function Sprite_Actor() {
    this.initialize.apply(this, arguments);
}

Sprite_Actor.prototype = Object.create(Sprite_Battler.prototype);
Sprite_Actor.prototype.constructor = Sprite_Actor;

/* 动作 */
Sprite_Actor.MOTIONS = {
    walk:     { index: 0,  loop: true  },  // 行走 
    wait:     { index: 1,  loop: true  },  // 待机 
    chant:    { index: 2,  loop: true  },  // 吟唱 
    guard:    { index: 3,  loop: true  },  // 防御 
    damage:   { index: 4,  loop: false },  // 受伤 
    evade:    { index: 5,  loop: false },  // 躲避 
    thrust:   { index: 6,  loop: false },  // 突刺 
    swing:    { index: 7,  loop: false },  // 挥舞 
    missile:  { index: 8,  loop: false },  // 飞行道具 
    skill:    { index: 9,  loop: false },  // 技能 
    spell:    { index: 10, loop: false },  // 魔法 
    item:     { index: 11, loop: false },  // 物品 
    escape:   { index: 12, loop: true  },  // 逃跑 
    victory:  { index: 13, loop: true  },  // 胜利 
    dying:    { index: 14, loop: true  },  // 频死 
    abnormal: { index: 15, loop: true  },  // 状态异常 
    sleep:    { index: 16, loop: true  },  // 睡眠 
    dead:     { index: 17, loop: true  }   // 死亡 
};

/* 初始化 */
Sprite_Actor.prototype.initialize = function(battler) {
    Sprite_Battler.prototype.initialize.call(this, battler);
    this.moveToStartPosition();
};

/* 初始化成员 */
Sprite_Actor.prototype.initMembers = function() {
    Sprite_Battler.prototype.initMembers.call(this);
    this._battlerName = '';
    this._motion = null;
    this._motionCount = 0;
    this._pattern = 0;
    this.createShadowSprite();
    this.createWeaponSprite();
    this.createMainSprite();
    this.createStateSprite();
};

/* 创建主精灵 */
Sprite_Actor.prototype.createMainSprite = function() {
    this._mainSprite = new Sprite_Base();
    this._mainSprite.anchor.x = 0.5;
    this._mainSprite.anchor.y = 1;
    this.addChild(this._mainSprite);
    this._effectTarget = this._mainSprite;
};

/* 创建影子精灵 */
Sprite_Actor.prototype.createShadowSprite = function() {
    this._shadowSprite = new Sprite();
    this._shadowSprite.bitmap = ImageManager.loadSystem('Shadow2');
    this._shadowSprite.anchor.x = 0.5;
    this._shadowSprite.anchor.y = 0.5;
    this._shadowSprite.y = -2;
    this.addChild(this._shadowSprite);
};

/* 创建武器精灵 */
Sprite_Actor.prototype.createWeaponSprite = function() {
    this._weaponSprite = new Sprite_Weapon();
    this.addChild(this._weaponSprite);
};

/* 创建状态精灵 */
Sprite_Actor.prototype.createStateSprite = function() {
    this._stateSprite = new Sprite_StateOverlay();
    this.addChild(this._stateSprite);
};

/* 设置战斗者 */
Sprite_Actor.prototype.setBattler = function(battler) {
    Sprite_Battler.prototype.setBattler.call(this, battler);
    var changed = (battler !== this._actor);
    if (changed) {
        this._actor = battler;
        if (battler) {
            this.setActorHome(battler.index());
        }
        this.startEntryMotion();
        this._stateSprite.setup(battler);
    }
};

/* 移动到开始位置 */
Sprite_Actor.prototype.moveToStartPosition = function() {
    this.startMove(300, 0, 0);
};

/* 设置角色家 */
Sprite_Actor.prototype.setActorHome = function(index) {
    this.setHome(600 + index * 32, 280 + index * 48);
};

/* 更新 */
Sprite_Actor.prototype.update = function() {
    Sprite_Battler.prototype.update.call(this);
    this.updateShadow();
    if (this._actor) {
        this.updateMotion();
    }
};

/* 更新影子 */
Sprite_Actor.prototype.updateShadow = function() {
    this._shadowSprite.visible = !!this._actor;
};

/* 更新主函数 */
Sprite_Actor.prototype.updateMain = function() {
    Sprite_Battler.prototype.updateMain.call(this);
    if (this._actor.isSpriteVisible() &amp;&amp; !this.isMoving()) {
        this.updateTargetPosition();
    }
};

/* 设置动作 */
Sprite_Actor.prototype.setupMotion = function() {
    if (this._actor.isMotionRequested()) {
        this.startMotion(this._actor.motionType());
        this._actor.clearMotion();
    }
};

/* 设置武器动画 */
Sprite_Actor.prototype.setupWeaponAnimation = function() {
    if (this._actor.isWeaponAnimationRequested()) {
        this._weaponSprite.setup(this._actor.weaponImageId());
        this._actor.clearWeaponAnimation();
    }
};

/* 开始动作 */
Sprite_Actor.prototype.startMotion = function(motionType) {
    var newMotion = Sprite_Actor.MOTIONS[motionType];
    if (this._motion !== newMotion) {
        this._motion = newMotion;
        this._motionCount = 0;
        this._pattern = 0;
    }
};

/* 更新目标位置 */
Sprite_Actor.prototype.updateTargetPosition = function() {
    if (this._actor.isInputting() || this._actor.isActing()) {
        this.stepForward();
    } else if (this._actor.canMove() &amp;&amp; BattleManager.isEscaped()) {
        this.retreat();
    } else if (!this.inHomePosition()) {
        this.stepBack();
    }
};

/* 更新位图 */
Sprite_Actor.prototype.updateBitmap = function() {
    Sprite_Battler.prototype.updateBitmap.call(this);
    var name = this._actor.battlerName();
    if (this._battlerName !== name) {
        this._battlerName = name;
        this._mainSprite.bitmap = ImageManager.loadSvActor(name);
    }
};

/* 更新帧 */
Sprite_Actor.prototype.updateFrame = function() {
    Sprite_Battler.prototype.updateFrame.call(this);
    var bitmap = this._mainSprite.bitmap;
    if (bitmap) {
        var motionIndex = this._motion ? this._motion.index : 0;
        var pattern = this._pattern &lt; 3 ? this._pattern : 1;
        var cw = bitmap.width / 9;
        var ch = bitmap.height / 6;
        var cx = Math.floor(motionIndex / 6) * 3 + pattern;
        var cy = motionIndex % 6;
        this._mainSprite.setFrame(cx * cw, cy * ch, cw, ch);
    }
};

/* 更新移动 */
Sprite_Actor.prototype.updateMove = function() {
    var bitmap = this._mainSprite.bitmap;
    if (!bitmap || bitmap.isReady()) {
        Sprite_Battler.prototype.updateMove.call(this);
    }
};

/* 更新动作 */
Sprite_Actor.prototype.updateMotion = function() {
    this.setupMotion();
    this.setupWeaponAnimation();
    if (this._actor.isMotionRefreshRequested()) {
        this.refreshMotion();
        this._actor.clearMotion();
    }
    this.updateMotionCount();
};

/* 更新动作计数 */
Sprite_Actor.prototype.updateMotionCount = function() {
    if (this._motion &amp;&amp; this._motionCount &gt;= this.motionSpeed()) {
        if (this._motion.loop) {
            this._pattern = (this._pattern + 1) % 4;
        } else if (this._pattern &lt; 2) {
            this._pattern;
        } else {
            this.refreshMotion();
        }
        this._motionCount = 0;
    }
};

/* 动作速度 */
Sprite_Actor.prototype.motionSpeed = function() {
    return 12;
};

/* 刷新动作 */
Sprite_Actor.prototype.refreshMotion = function() {
    var actor = this._actor;
    var motionGuard = Sprite_Actor.MOTIONS['guard'];
    if (actor) {
        if (this._motion === motionGuard &amp;&amp; !BattleManager.isInputting()) {
                return;
        }
        var stateMotion = actor.stateMotionIndex();
        if (actor.isInputting() || actor.isActing()) {
            this.startMotion('walk');
        } else if (stateMotion === 3) {
            this.startMotion('dead');
        } else if (stateMotion === 2) {
            this.startMotion('sleep');
        } else if (actor.isChanting()) {
            this.startMotion('chant');
        } else if (actor.isGuard() || actor.isGuardWaiting()) {
            this.startMotion('guard');
        } else if (stateMotion === 1) {
            this.startMotion('abnormal');
        } else if (actor.isDying()) {
            this.startMotion('dying');
        } else if (actor.isUndecided()) {
            this.startMotion('walk');
        } else {
            this.startMotion('wait');
        }
    }
};

/* 开始进入动作 */
Sprite_Actor.prototype.startEntryMotion = function() {
    if (this._actor &amp;&amp; this._actor.canMove()) {
        this.startMotion('walk');
        this.startMove(0, 0, 30);
    } else if (!this.isMoving()) {
        this.refreshMotion();
        this.startMove(0, 0, 0);
    }
};

/* 踏步向前 */
Sprite_Actor.prototype.stepForward = function() {
    this.startMove(-48, 0, 12);
};

/* 踏步向后 */
Sprite_Actor.prototype.stepBack = function() {
    this.startMove(0, 0, 12);
};

/* 撤退 */
Sprite_Actor.prototype.retreat = function() {
    this.startMove(300, 0, 30);
};

/* 当移动结束 */
Sprite_Actor.prototype.onMoveEnd = function() {
    Sprite_Battler.prototype.onMoveEnd.call(this);
    if (!BattleManager.isBattleEnd()) {
        this.refreshMotion();
    }
};

/* 伤害的偏移坐标 X */
Sprite_Actor.prototype.damageOffsetX = function() {
    return -32;
};

/* 伤害的偏移坐标 Y */
Sprite_Actor.prototype.damageOffsetY = function() {
    return 0;
};

//-----------------------------------------------------------------------------
// 精灵_敌人 
// Sprite_Enemy
//
// 显示敌人的精灵。 
// The sprite for displaying an enemy.

function Sprite_Enemy() {
    this.initialize.apply(this, arguments);
}

Sprite_Enemy.prototype = Object.create(Sprite_Battler.prototype);
Sprite_Enemy.prototype.constructor = Sprite_Enemy;

/* 初始化 */
Sprite_Enemy.prototype.initialize = function(battler) {
    Sprite_Battler.prototype.initialize.call(this, battler);
};

/* 初始化成员 */
Sprite_Enemy.prototype.initMembers = function() {
    Sprite_Battler.prototype.initMembers.call(this);
    this._enemy = null;
    this._appeared = false;
    this._battlerName = '';
    this._battlerHue = 0;
    this._effectType = null;
    this._effectDuration = 0;
    this._shake = 0;
    this.createStateIconSprite();
};

/* 创建状态图标精灵 */
Sprite_Enemy.prototype.createStateIconSprite = function() {
    this._stateIconSprite = new Sprite_StateIcon();
    this.addChild(this._stateIconSprite);
};

/* 设置战斗者 */
Sprite_Enemy.prototype.setBattler = function(battler) {
    Sprite_Battler.prototype.setBattler.call(this, battler);
    this._enemy = battler;
    this.setHome(battler.screenX(), battler.screenY());
    this._stateIconSprite.setup(battler);
};

/* 更新 */
Sprite_Enemy.prototype.update = function() {
    Sprite_Battler.prototype.update.call(this);
    if (this._enemy) {
        this.updateEffect();
        this.updateStateSprite();
    }
};

/* 更新位图 */
Sprite_Enemy.prototype.updateBitmap = function() {
    Sprite_Battler.prototype.updateBitmap.call(this);
    var name = this._enemy.battlerName();
    var hue = this._enemy.battlerHue();
    if (this._battlerName !== name || this._battlerHue !== hue) {
        this._battlerName = name;
        this._battlerHue = hue;
        this.loadBitmap(name, hue);
        this.initVisibility();
    }
};

/* 加载位图 */
Sprite_Enemy.prototype.loadBitmap = function(name, hue) {
    if ($gameSystem.isSideView()) {
        this.bitmap = ImageManager.loadSvEnemy(name, hue);
    } else {
        this.bitmap = ImageManager.loadEnemy(name, hue);
    }
};

/* 更新帧 */
Sprite_Enemy.prototype.updateFrame = function() {
    Sprite_Battler.prototype.updateFrame.call(this);
    var frameHeight = this.bitmap.height;
    if (this._effectType === 'bossCollapse') {
        frameHeight = this._effectDuration;
    }
    this.setFrame(0, 0, this.bitmap.width, frameHeight);
};

/* 更新位置 */
Sprite_Enemy.prototype.updatePosition = function() {
    Sprite_Battler.prototype.updatePosition.call(this);
    this.x = this._shake;
};

/* 更新状态精灵 */
Sprite_Enemy.prototype.updateStateSprite = function() {
    this._stateIconSprite.y = -Math.round((this.bitmap.height + 40) * 0.9);
    if (this._stateIconSprite.y &lt; 20 - this.y) {
        this._stateIconSprite.y = 20 - this.y;
    }
};

/* 初始化可见性 */
Sprite_Enemy.prototype.initVisibility = function() {
    this._appeared = this._enemy.isAlive();
    if (!this._appeared) {
        this.opacity = 0;
    }
};

/* 设置效果 */
Sprite_Enemy.prototype.setupEffect = function() {
    if (this._appeared &amp;&amp; this._enemy.isEffectRequested()) {
        this.startEffect(this._enemy.effectType());
        this._enemy.clearEffect();
    }
    if (!this._appeared &amp;&amp; this._enemy.isAlive()) {
        this.startEffect('appear');
    } else if (this._appeared &amp;&amp; this._enemy.isHidden()) {
        this.startEffect('disappear');
    }
};

/* 开始效果 */
Sprite_Enemy.prototype.startEffect = function(effectType) {
    this._effectType = effectType;
    switch (this._effectType) {
    case 'appear': // 出现 
        this.startAppear();
        break;
    case 'disappear':  // 消失 
        this.startDisappear();
        break;
    case 'whiten':  // 变白 
        this.startWhiten();
        break;
    case 'blink':  // 闪烁 
        this.startBlink();
        break;
    case 'collapse': // 倒下（消失效果-正常） 
        this.startCollapse();
        break;
    case 'bossCollapse': // BOSS倒下（消失效果-BOSS） 
        this.startBossCollapse();
        break;
    case 'instantCollapse':  // 瞬间倒下（消失效果-瞬间消失） 
        this.startInstantCollapse();
        break;
    }
    this.revertToNormal();
};

/* 开始出现 */
Sprite_Enemy.prototype.startAppear = function() {
    this._effectDuration = 16;
    this._appeared = true;
};

/* 开始消失 */
Sprite_Enemy.prototype.startDisappear = function() {
    this._effectDuration = 32;
    this._appeared = false;
};

/* 开始变白 */
Sprite_Enemy.prototype.startWhiten = function() {
    this._effectDuration = 16;
};

/* 开始闪烁 */
Sprite_Enemy.prototype.startBlink = function() {
    this._effectDuration = 20;
};

/* 开始倒下 */
Sprite_Enemy.prototype.startCollapse = function() {
    this._effectDuration = 32;
    this._appeared = false;
};

/* 开始 BOSS 倒下 */
Sprite_Enemy.prototype.startBossCollapse = function() {
    this._effectDuration = this.bitmap.height;
    this._appeared = false;
};

/* 开始瞬间倒下 */
Sprite_Enemy.prototype.startInstantCollapse = function() {
    this._effectDuration = 16;
    this._appeared = false;
};

/* 更新效果 */
Sprite_Enemy.prototype.updateEffect = function() {
    this.setupEffect();
    if (this._effectDuration &gt; 0) {
        this._effectDuration--;
        switch (this._effectType) {
        case 'whiten':
            this.updateWhiten();
            break;
        case 'blink':
            this.updateBlink();
            break;
        case 'appear':
            this.updateAppear();
            break;
        case 'disappear':
            this.updateDisappear();
            break;
        case 'collapse':
            this.updateCollapse();
            break;
        case 'bossCollapse':
            this.updateBossCollapse();
            break;
        case 'instantCollapse':
            this.updateInstantCollapse();
            break;
        }
        if (this._effectDuration === 0) {
            this._effectType = null;
        }
    }
};

/* 是否效果中 */
Sprite_Enemy.prototype.isEffecting = function() {
    return this._effectType !== null;
};

/* 回到普通 */
Sprite_Enemy.prototype.revertToNormal = function() {
    this._shake = 0;
    this.blendMode = 0;
    this.opacity = 255;
    this.setBlendColor([0, 0, 0, 0]);
};

/* 更新变白 */
Sprite_Enemy.prototype.updateWhiten = function() {
    var alpha = 128 - (16 - this._effectDuration) * 10;
    this.setBlendColor([255, 255, 255, alpha]);
};

/* 更新闪烁 */
Sprite_Enemy.prototype.updateBlink = function() {
    this.opacity = (this._effectDuration % 10 &lt; 5) ? 255 : 0;
};

/* 更新出现 */
Sprite_Enemy.prototype.updateAppear = function() {
    this.opacity = (16 - this._effectDuration) * 16;
};

/* 更新消失 */
Sprite_Enemy.prototype.updateDisappear = function() {
    this.opacity = 256 - (32 - this._effectDuration) * 10;
};

/* 更新倒下 */
Sprite_Enemy.prototype.updateCollapse = function() {
    this.blendMode = Graphics.BLEND_ADD;
    this.setBlendColor([255, 128, 128, 128]);
    this.opacity *= this._effectDuration / (this._effectDuration + 1);
};

/* 更新 BOSS 倒下 */
Sprite_Enemy.prototype.updateBossCollapse = function() {
    this._shake = this._effectDuration % 2 * 4 - 2;
    this.blendMode = Graphics.BLEND_ADD;
    this.opacity *= this._effectDuration / (this._effectDuration + 1);
    this.setBlendColor([255, 255, 255, 255 - this.opacity]);
    if (this._effectDuration % 20 === 19) {
        SoundManager.playBossCollapse2();
    }
};

/* 更新瞬间倒下 */
Sprite_Enemy.prototype.updateInstantCollapse = function() {
    this.opacity = 0;
};

/* 伤害的偏移坐标 X */
Sprite_Enemy.prototype.damageOffsetX = function() {
    return 0;
};

/* 伤害的偏移坐标 Y */
Sprite_Enemy.prototype.damageOffsetY = function() {
    return -8;
};

//-----------------------------------------------------------------------------
// 精灵_动画 
// Sprite_Animation
//
// 显示动画的精灵。 
// The sprite for displaying an animation.

function Sprite_Animation() {
    this.initialize.apply(this, arguments);
}

Sprite_Animation.prototype = Object.create(Sprite.prototype);
Sprite_Animation.prototype.constructor = Sprite_Animation;

Sprite_Animation._checker1 = {};
Sprite_Animation._checker2 = {};

/* 初始化 */
Sprite_Animation.prototype.initialize = function() {
    Sprite.prototype.initialize.call(this);
    this._reduceArtifacts = true;
    this.initMembers();
};

/* 初始化成员 */
Sprite_Animation.prototype.initMembers = function() {
    this._target = null;
    this._animation = null;
    this._mirror = false;
    this._delay = 0;
    this._rate = 4;
    this._duration = 0;
    this._flashColor = [0, 0, 0, 0];
    this._flashDuration = 0;
    this._screenFlashDuration = 0;
    this._hidingDuration = 0;
    this._bitmap1 = null;
    this._bitmap2 = null;
    this._cellSprites = [];
    this._screenFlashSprite = null;
    this._duplicated = false;
    this.z = 8;
};

/* 设置 */
Sprite_Animation.prototype.setup = function(target, animation, mirror, delay) {
    this._target = target;
    this._animation = animation;
    this._mirror = mirror;
    this._delay = delay;
    if (this._animation) {
        this.remove();
        this.setupRate();
        this.setupDuration();
        this.loadBitmaps();
        this.createSprites();
    }
};

/* 移除 */
Sprite_Animation.prototype.remove = function() {
    if (this.parent &amp;&amp; this.parent.removeChild(this)) {
        this._target.setBlendColor([0, 0, 0, 0]);
        this._target.show();
    }
};

/* 设置倍率 */
Sprite_Animation.prototype.setupRate = function() {
    this._rate = 4;
};

/* 设置持续时间 */
Sprite_Animation.prototype.setupDuration = function() {
    this._duration = this._animation.frames.length * this._rate + 1;
};

/* 更新 */
Sprite_Animation.prototype.update = function() {
    Sprite.prototype.update.call(this);
    this.updateMain();
    this.updateFlash();
    this.updateScreenFlash();
    this.updateHiding();
    Sprite_Animation._checker1 = {};
    Sprite_Animation._checker2 = {};
};

/* 更新闪烁 */
Sprite_Animation.prototype.updateFlash = function() {
    if (this._flashDuration &gt; 0) {
        var d = this._flashDuration--;
        this._flashColor[3] *= (d - 1) / d;
        this._target.setBlendColor(this._flashColor);
    }
};

/* 更新画面闪烁 */
Sprite_Animation.prototype.updateScreenFlash = function() {
    if (this._screenFlashDuration &gt; 0) {
        var d = this._screenFlashDuration--;
        if (this._screenFlashSprite) {
            this._screenFlashSprite.x = -this.absoluteX();
            this._screenFlashSprite.y = -this.absoluteY();
            this._screenFlashSprite.opacity *= (d - 1) / d;
            this._screenFlashSprite.visible = (this._screenFlashDuration &gt; 0);
        }
    }
};

/* 绝对坐标 X */
Sprite_Animation.prototype.absoluteX = function() {
    var x = 0;
    var object = this;
    while (object) {
        x += object.x;
        object = object.parent;
    }
    return x;
};

/* 绝对坐标 Y */
Sprite_Animation.prototype.absoluteY = function() {
    var y = 0;
    var object = this;
    while (object) {
        y += object.y;
        object = object.parent;
    }
    return y;
};

/* 更新隐藏 */
Sprite_Animation.prototype.updateHiding = function() {
    if (this._hidingDuration &gt; 0) {
        this._hidingDuration--;
        if (this._hidingDuration === 0) {
            this._target.show();
        }
    }
};

/* 是否播放中 */
Sprite_Animation.prototype.isPlaying = function() {
    return this._duration &gt; 0;
};

/* 加载位图 */
Sprite_Animation.prototype.loadBitmaps = function() {
    var name1 = this._animation.animation1Name;
    var name2 = this._animation.animation2Name;
    var hue1 = this._animation.animation1Hue;
    var hue2 = this._animation.animation2Hue;
    this._bitmap1 = ImageManager.loadAnimation(name1, hue1);
    this._bitmap2 = ImageManager.loadAnimation(name2, hue2);
};

/* 是否准备好 */
Sprite_Animation.prototype.isReady = function() {
    return this._bitmap1 &amp;&amp; this._bitmap1.isReady() &amp;&amp; this._bitmap2 &amp;&amp; this._bitmap2.isReady();
};

/* 创建精灵 */
Sprite_Animation.prototype.createSprites = function() {
    if (!Sprite_Animation._checker2[this._animation]) {
        this.createCellSprites();
        if (this._animation.position === 3) {
            Sprite_Animation._checker2[this._animation] = true;
        }
        this.createScreenFlashSprite();
    }
    if (Sprite_Animation._checker1[this._animation]) {
        this._duplicated = true;
    } else {
        this._duplicated = false;
        if (this._animation.position === 3) {
            Sprite_Animation._checker1[this._animation] = true;
        }
    }
};

/* 创建单元精灵 */
Sprite_Animation.prototype.createCellSprites = function() {
    this._cellSprites = [];
    for (var i = 0; i &lt; 16; i) {
        var sprite = new Sprite();
        sprite.anchor.x = 0.5;
        sprite.anchor.y = 0.5;
        this._cellSprites.push(sprite);
        this.addChild(sprite);
    }
};

/* 创建画面闪烁精灵 */
Sprite_Animation.prototype.createScreenFlashSprite = function() {
    this._screenFlashSprite = new ScreenSprite();
    this.addChild(this._screenFlashSprite);
};

/* 更新主函数 */
Sprite_Animation.prototype.updateMain = function() {
    if (this.isPlaying() &amp;&amp; this.isReady()) {
        if (this._delay &gt; 0) {
            this._delay--;
        } else {
            this._duration--;
            this.updatePosition();
            if (this._duration % this._rate === 0) {
                this.updateFrame();
            }
        }
    }
};

/* 更新位置 */
Sprite_Animation.prototype.updatePosition = function() {
    if (this._animation.position === 3) {
        this.x = this.parent.width / 2;
        this.y = this.parent.height / 2;
    } else {
        var parent = this._target.parent;
        var grandparent = parent ? parent.parent : null;
        this.x = this._target.x;
        this.y = this._target.y;
        if (this.parent === grandparent) {
            this.x += parent.x;
            this.y += parent.y;
        }
        if (this._animation.position === 0) {
            this.y -= this._target.height;
        } else if (this._animation.position === 1) {
            this.y -= this._target.height / 2;
        }
    }
};

/* 更新帧 */
Sprite_Animation.prototype.updateFrame = function() {
    if (this._duration &gt; 0) {
        var frameIndex = this.currentFrameIndex();
        this.updateAllCellSprites(this._animation.frames[frameIndex]);
        this._animation.timings.forEach(function(timing) {
            if (timing.frame === frameIndex) {
                this.processTimingData(timing);
            }
        }, this);
    }
};

/* 当前帧索引 */
Sprite_Animation.prototype.currentFrameIndex = function() {
    return (this._animation.frames.length -
            Math.floor((this._duration + this._rate - 1) / this._rate));
};

/* 更新所有单元精灵 */
Sprite_Animation.prototype.updateAllCellSprites = function(frame) {
    for (var i = 0; i &lt; this._cellSprites.length; i) {
        var sprite = this._cellSprites[i];
        if (i &lt; frame.length) {
            this.updateCellSprite(sprite, frame[i]);
        } else {
            sprite.visible = false;
        }
    }
};

/* 更新单元精灵 */
Sprite_Animation.prototype.updateCellSprite = function(sprite, cell) {
    var pattern = cell[0];
    if (pattern &gt;= 0) {
        var sx = pattern % 5 * 192;
        var sy = Math.floor(pattern % 100 / 5) * 192;
        var mirror = this._mirror;
        sprite.bitmap = pattern &lt; 100 ? this._bitmap1 : this._bitmap2;
        sprite.setFrame(sx, sy, 192, 192);
        sprite.x = cell[1];
        sprite.y = cell[2];
        sprite.rotation = cell[4] * Math.PI / 180;
        sprite.scale.x = cell[3] / 100;

        if(cell[5]){
            sprite.scale.x *= -1;
        }
        if(mirror){
            sprite.x *= -1;
            sprite.rotation *= -1;
            sprite.scale.x *= -1;
        }

        sprite.scale.y = cell[3] / 100;
        sprite.opacity = cell[6];
        sprite.blendMode = cell[7];
        sprite.visible = true;
    } else {
        sprite.visible = false;
    }
};

/* 处理时间安排数据 */
Sprite_Animation.prototype.processTimingData = function(timing) {
    var duration = timing.flashDuration * this._rate;
    switch (timing.flashScope) {
    case 1:
        this.startFlash(timing.flashColor, duration);
        break;
    case 2:
        this.startScreenFlash(timing.flashColor, duration);
        break;
    case 3:
        this.startHiding(duration);
        break;
    }
    if (!this._duplicated &amp;&amp; timing.se) {
        AudioManager.playSe(timing.se);
    }
};

/* 开始闪烁 */
Sprite_Animation.prototype.startFlash = function(color, duration) {
    this._flashColor = color.clone();
    this._flashDuration = duration;
};

/* 开始画面闪烁 */
Sprite_Animation.prototype.startScreenFlash = function(color, duration) {
    this._screenFlashDuration = duration;
    if (this._screenFlashSprite) {
        this._screenFlashSprite.setColor(color[0], color[1], color[2]);
        this._screenFlashSprite.opacity = color[3];
    }
};

/* 开始隐藏 */
Sprite_Animation.prototype.startHiding = function(duration) {
    this._hidingDuration = duration;
    this._target.hide();
};

//-----------------------------------------------------------------------------
// 精灵_伤害 
// Sprite_Damage
//
// 显示弹出伤害的精灵。 
// The sprite for displaying a popup damage.

function Sprite_Damage() {
    this.initialize.apply(this, arguments);
}

Sprite_Damage.prototype = Object.create(Sprite.prototype);
Sprite_Damage.prototype.constructor = Sprite_Damage;

/* 初始化 */
Sprite_Damage.prototype.initialize = function() {
    Sprite.prototype.initialize.call(this);
    this._duration = 90;
    this._flashColor = [0, 0, 0, 0];
    this._flashDuration = 0;
    this._damageBitmap = ImageManager.loadSystem('Damage');
};

/* 设置 */
Sprite_Damage.prototype.setup = function(target) {
    var result = target.result();
    if (result.missed || result.evaded) {
        this.createMiss();
    } else if (result.hpAffected) {
        this.createDigits(0, result.hpDamage);
    } else if (target.isAlive() &amp;&amp; result.mpDamage !== 0) {
        this.createDigits(2, result.mpDamage);
    }
    if (result.critical) {
        this.setupCriticalEffect();
    }
};

/* 设置暴击效果 */
Sprite_Damage.prototype.setupCriticalEffect = function() {
    this._flashColor = [255, 0, 0, 160];
    this._flashDuration = 60;
};

/* 数字宽度 */
Sprite_Damage.prototype.digitWidth = function() {
    return this._damageBitmap ? this._damageBitmap.width / 10 : 0;
};

/* 数字高度 */
Sprite_Damage.prototype.digitHeight = function() {
    return this._damageBitmap ? this._damageBitmap.height / 5 : 0;
};

/* 创建未命中 */
Sprite_Damage.prototype.createMiss = function() {
    var w = this.digitWidth();
    var h = this.digitHeight();
    var sprite = this.createChildSprite();
    sprite.setFrame(0, 4 * h, 4 * w, h);
    sprite.dy = 0;
};

/* 创建数字 */
Sprite_Damage.prototype.createDigits = function(baseRow, value) {
    var string = Math.abs(value).toString();
    var row = baseRow + (value &lt; 0 ? 1 : 0);
    var w = this.digitWidth();
    var h = this.digitHeight();
    for (var i = 0; i &lt; string.length; i) {
        var sprite = this.createChildSprite();
        var n = Number(string[i]);
        sprite.setFrame(n * w, row * h, w, h);
        sprite.x = (i - (string.length - 1) / 2) * w;
        sprite.dy = -i;
    }
};

/* 创建子精灵 */
Sprite_Damage.prototype.createChildSprite = function() {
    var sprite = new Sprite();
    sprite.bitmap = this._damageBitmap;
    sprite.anchor.x = 0.5;
    sprite.anchor.y = 1;
    sprite.y = -40;
    sprite.ry = sprite.y;
    this.addChild(sprite);
    return sprite;
};

/* 更新 */
Sprite_Damage.prototype.update = function() {
    Sprite.prototype.update.call(this);
    if (this._duration &gt; 0) {
        this._duration--;
        for (var i = 0; i &lt; this.children.length; i) {
            this.updateChild(this.children[i]);
        }
    }
    this.updateFlash();
    this.updateOpacity();
};

/* 更新子元素 */
Sprite_Damage.prototype.updateChild = function(sprite) {
    sprite.dy += 0.5;
    sprite.ry += sprite.dy;
    if (sprite.ry &gt;= 0) {
        sprite.ry = 0;
        sprite.dy *= -0.6;
    }
    sprite.y = Math.round(sprite.ry);
    sprite.setBlendColor(this._flashColor);
};

/* 更新闪烁 */
Sprite_Damage.prototype.updateFlash = function() {
    if (this._flashDuration &gt; 0) {
        var d = this._flashDuration--;
        this._flashColor[3] *= (d - 1) / d;
    }
};

/* 更新不透明度 */
Sprite_Damage.prototype.updateOpacity = function() {
    if (this._duration &lt; 10) {
        this.opacity = 255 * this._duration / 10;
    }
};

/* 是否播放中 */
Sprite_Damage.prototype.isPlaying = function() {
    return this._duration &gt; 0;
};

//-----------------------------------------------------------------------------
// 精灵_状态图标 
// Sprite_StateIcon
//
// 显示状态图标的精灵。 
// The sprite for displaying state icons.

function Sprite_StateIcon() {
    this.initialize.apply(this, arguments);
}

Sprite_StateIcon.prototype = Object.create(Sprite.prototype);
Sprite_StateIcon.prototype.constructor = Sprite_StateIcon;

/* 初始化 */
Sprite_StateIcon.prototype.initialize = function() {
    Sprite.prototype.initialize.call(this);
    this.initMembers();
    this.loadBitmap();
};

Sprite_StateIcon._iconWidth  = 32;  // 图标宽度 
Sprite_StateIcon._iconHeight = 32;  // 图标高度 

/* 初始化成员 */
Sprite_StateIcon.prototype.initMembers = function() {
    this._battler = null;
    this._iconIndex = 0;
    this._animationCount = 0;
    this._animationIndex = 0;
    this.anchor.x = 0.5;
    this.anchor.y = 0.5;
};

/* 加载位图 */
Sprite_StateIcon.prototype.loadBitmap = function() {
    this.bitmap = ImageManager.loadSystem('IconSet');
    this.setFrame(0, 0, 0, 0);
};

/* 设置 */
Sprite_StateIcon.prototype.setup = function(battler) {
    this._battler = battler;
};

/* 更新 */
Sprite_StateIcon.prototype.update = function() {
    Sprite.prototype.update.call(this);
    this._animationCount;
    if (this._animationCount &gt;= this.animationWait()) {
        this.updateIcon();
        this.updateFrame();
        this._animationCount = 0;
    }
};

/* 动画等待帧数 */
Sprite_StateIcon.prototype.animationWait = function() {
    return 40;
};

/* 更新图标 */
Sprite_StateIcon.prototype.updateIcon = function() {
    var icons = [];
    if (this._battler &amp;&amp; this._battler.isAlive()) {
        icons = this._battler.allIcons();
    }
    if (icons.length &gt; 0) {
        this._animationIndex;
        if (this._animationIndex &gt;= icons.length) {
            this._animationIndex = 0;
        }
        this._iconIndex = icons[this._animationIndex];
    } else {
        this._animationIndex = 0;
        this._iconIndex = 0;
    }
};

/* 更新帧 */
Sprite_StateIcon.prototype.updateFrame = function() {
    var pw = Sprite_StateIcon._iconWidth;
    var ph = Sprite_StateIcon._iconHeight;
    var sx = this._iconIndex % 16 * pw;
    var sy = Math.floor(this._iconIndex / 16) * ph;
    this.setFrame(sx, sy, pw, ph);
};

//-----------------------------------------------------------------------------
// 精灵_状态覆盖 
// Sprite_StateOverlay
//
// 显示状态的覆盖图像的精灵。 
// The sprite for displaying an overlay image for a state.

function Sprite_StateOverlay() {
    this.initialize.apply(this, arguments);
}

Sprite_StateOverlay.prototype = Object.create(Sprite_Base.prototype);
Sprite_StateOverlay.prototype.constructor = Sprite_StateOverlay;

/* 初始化 */
Sprite_StateOverlay.prototype.initialize = function() {
    Sprite_Base.prototype.initialize.call(this);
    this.initMembers();
    this.loadBitmap();
};

/* 初始化成员 */
Sprite_StateOverlay.prototype.initMembers = function() {
    this._battler = null;
    this._overlayIndex = 0;
    this._animationCount = 0;
    this._pattern = 0;
    this.anchor.x = 0.5;
    this.anchor.y = 1;
};

/* 加载位图 */
Sprite_StateOverlay.prototype.loadBitmap = function() {
    this.bitmap = ImageManager.loadSystem('States');
    this.setFrame(0, 0, 0, 0);
};

/* 设置 */
Sprite_StateOverlay.prototype.setup = function(battler) {
    this._battler = battler;
};

/* 更新 */
Sprite_StateOverlay.prototype.update = function() {
    Sprite_Base.prototype.update.call(this);
    this._animationCount;
    if (this._animationCount &gt;= this.animationWait()) {
        this.updatePattern();
        this.updateFrame();
        this._animationCount = 0;
    }
};

/* 动画等待帧数 */
Sprite_StateOverlay.prototype.animationWait = function() {
    return 8;
};

/* 更新图案 */
Sprite_StateOverlay.prototype.updatePattern = function() {
    this._pattern;
    this._pattern %= 8;
    if (this._battler) {
        this._overlayIndex = this._battler.stateOverlayIndex();
    }
};

/* 更新帧 */
Sprite_StateOverlay.prototype.updateFrame = function() {
    if (this._overlayIndex &gt; 0) {
        var w = 96;
        var h = 96;
        var sx = this._pattern * w;
        var sy = (this._overlayIndex - 1) * h;
        this.setFrame(sx, sy, w, h);
    } else {
        this.setFrame(0, 0, 0, 0);
    }
};

//-----------------------------------------------------------------------------
// 精灵_武器 
// Sprite_Weapon
//
// 显示攻击的武器图像的精灵。 
// The sprite for displaying a weapon image for attacking.

function Sprite_Weapon() {
    this.initialize.apply(this, arguments);
}

Sprite_Weapon.prototype = Object.create(Sprite_Base.prototype);
Sprite_Weapon.prototype.constructor = Sprite_Weapon;

/* 初始化 */
Sprite_Weapon.prototype.initialize = function() {
    Sprite_Base.prototype.initialize.call(this);
    this.initMembers();
};

/* 初始化成员 */
Sprite_Weapon.prototype.initMembers = function() {
    this._weaponImageId = 0;
    this._animationCount = 0;
    this._pattern = 0;
    this.anchor.x = 0.5;
    this.anchor.y = 1;
    this.x = -16;
};

/* 设置 */
Sprite_Weapon.prototype.setup = function(weaponImageId) {
    this._weaponImageId = weaponImageId;
    this._animationCount = 0;
    this._pattern = 0;
    this.loadBitmap();
    this.updateFrame();
};

/* 更新 */
Sprite_Weapon.prototype.update = function() {
    Sprite_Base.prototype.update.call(this);
    this._animationCount;
    if (this._animationCount &gt;= this.animationWait()) {
        this.updatePattern();
        this.updateFrame();
        this._animationCount = 0;
    }
};

/* 动画等待帧数 */
Sprite_Weapon.prototype.animationWait = function() {
    return 12;
};

/* 更新图案 */
Sprite_Weapon.prototype.updatePattern = function() {
    this._pattern;
    if (this._pattern &gt;= 3) {
        this._weaponImageId = 0;
    }
};

/* 加载位图 */
Sprite_Weapon.prototype.loadBitmap = function() {
    var pageId = Math.floor((this._weaponImageId - 1) / 12) + 1;
    if (pageId &gt;= 1) {
        this.bitmap = ImageManager.loadSystem('Weapons' + pageId);
    } else {
        this.bitmap = ImageManager.loadSystem('');
    }
};

/* 更新帧 */
Sprite_Weapon.prototype.updateFrame = function() {
    if (this._weaponImageId &gt; 0) {
        var index = (this._weaponImageId - 1) % 12;
        var w = 96;
        var h = 64;
        var sx = (Math.floor(index / 6) * 3 + this._pattern) * w;
        var sy = Math.floor(index % 6) * h;
        this.setFrame(sx, sy, w, h);
    } else {
        this.setFrame(0, 0, 0, 0);
    }
};

/* 是否播放中 */
Sprite_Weapon.prototype.isPlaying = function() {
    return this._weaponImageId &gt; 0;
};

//-----------------------------------------------------------------------------
// 精灵_气泡 
// Sprite_Balloon
//
// 显示气泡图标的精灵。 
// The sprite for displaying a balloon icon.

function Sprite_Balloon() {
    this.initialize.apply(this, arguments);
}

Sprite_Balloon.prototype = Object.create(Sprite_Base.prototype);
Sprite_Balloon.prototype.constructor = Sprite_Balloon;

/* 初始化 */
Sprite_Balloon.prototype.initialize = function() {
    Sprite_Base.prototype.initialize.call(this);
    this.initMembers();
    this.loadBitmap();
};

/* 初始化成员 */
Sprite_Balloon.prototype.initMembers = function() {
    this._balloonId = 0;
    this._duration = 0;
    this.anchor.x = 0.5;
    this.anchor.y = 1;
    this.z = 7;
};

/* 加载位图 */
Sprite_Balloon.prototype.loadBitmap = function() {
    this.bitmap = ImageManager.loadSystem('Balloon');
    this.setFrame(0, 0, 0, 0);
};

/* 设置 */
Sprite_Balloon.prototype.setup = function(balloonId) {
    this._balloonId = balloonId;
    this._duration = 8 * this.speed() + this.waitTime();
};

/* 更新 */
Sprite_Balloon.prototype.update = function() {
    Sprite_Base.prototype.update.call(this);
    if (this._duration &gt; 0) {
        this._duration--;
        if (this._duration &gt; 0) {
            this.updateFrame();
        }
    }
};

/* 更新帧 */
Sprite_Balloon.prototype.updateFrame = function() {
    var w = 48;
    var h = 48;
    var sx = this.frameIndex() * w;
    var sy = (this._balloonId - 1) * h;
    this.setFrame(sx, sy, w, h);
};

/* 速度 */
Sprite_Balloon.prototype.speed = function() {
    return 8;
};

/* 等待时间 */
Sprite_Balloon.prototype.waitTime = function() {
    return 12;
};

/* 帧索引 */
Sprite_Balloon.prototype.frameIndex = function() {
    var index = (this._duration - this.waitTime()) / this.speed();
    return 7 - Math.max(Math.floor(index), 0);
};

/* 是否播放中 */
Sprite_Balloon.prototype.isPlaying = function() {
    return this._duration &gt; 0;
};

//-----------------------------------------------------------------------------
// 精灵_图片 
// Sprite_Picture
//
// 显示图片的精灵。 
// The sprite for displaying a picture.

function Sprite_Picture() {
    this.initialize.apply(this, arguments);
}

Sprite_Picture.prototype = Object.create(Sprite.prototype);
Sprite_Picture.prototype.constructor = Sprite_Picture;

/* 初始化 */
Sprite_Picture.prototype.initialize = function(pictureId) {
    Sprite.prototype.initialize.call(this);
    this._pictureId = pictureId;
    this._pictureName = '';
    this._isPicture = true;
    this.update();
};

/* 图片 */
Sprite_Picture.prototype.picture = function() {
    return $gameScreen.picture(this._pictureId);
};

/* 更新 */
Sprite_Picture.prototype.update = function() {
    Sprite.prototype.update.call(this);
    this.updateBitmap();
    if (this.visible) {
        this.updateOrigin();
        this.updatePosition();
        this.updateScale();
        this.updateTone();
        this.updateOther();
    }
};

/* 更新位图 */
Sprite_Picture.prototype.updateBitmap = function() {
    var picture = this.picture();
    if (picture) {
        var pictureName = picture.name();
        if (this._pictureName !== pictureName) {
            this._pictureName = pictureName;
            this.loadBitmap();
        }
        this.visible = true;
    } else {
        this._pictureName = '';
        this.bitmap = null;
        this.visible = false;
    }
};

/* 更新起始 */
Sprite_Picture.prototype.updateOrigin = function() {
    var picture = this.picture();
    if (picture.origin() === 0) {
        this.anchor.x = 0;
        this.anchor.y = 0;
    } else {
        this.anchor.x = 0.5;
        this.anchor.y = 0.5;
    }
};

/* 更新位置 */
Sprite_Picture.prototype.updatePosition = function() {
    var picture = this.picture();
    this.x = Math.floor(picture.x());
    this.y = Math.floor(picture.y());
};

/* 更新缩放 */
Sprite_Picture.prototype.updateScale = function() {
    var picture = this.picture();
    this.scale.x = picture.scaleX() / 100;
    this.scale.y = picture.scaleY() / 100;
};

/* 更新色调 */
Sprite_Picture.prototype.updateTone = function() {
    var picture = this.picture();
    if (picture.tone()) {
        this.setColorTone(picture.tone());
    } else {
        this.setColorTone([0, 0, 0, 0]);
    }
};

/* 更新其它 */
Sprite_Picture.prototype.updateOther = function() {
    var picture = this.picture();
    this.opacity = picture.opacity();
    this.blendMode = picture.blendMode();
    this.rotation = picture.angle() * Math.PI / 180;
};

/* 加载位图 */
Sprite_Picture.prototype.loadBitmap = function() {
    this.bitmap = ImageManager.loadPicture(this._pictureName);
};

//-----------------------------------------------------------------------------
// 精灵_计时器 
// Sprite_Timer
//
// 显示计时器的精灵。 
// The sprite for displaying the timer.

function Sprite_Timer() {
    this.initialize.apply(this, arguments);
}

Sprite_Timer.prototype = Object.create(Sprite.prototype);
Sprite_Timer.prototype.constructor = Sprite_Timer;

/* 初始化 */
Sprite_Timer.prototype.initialize = function() {
    Sprite.prototype.initialize.call(this);
    this._seconds = 0;
    this.createBitmap();
    this.update();
};

/* 创建位图 */
Sprite_Timer.prototype.createBitmap = function() {
    this.bitmap = new Bitmap(96, 48);
    this.bitmap.fontSize = 32;
};

/* 更新 */
Sprite_Timer.prototype.update = function() {
    Sprite.prototype.update.call(this);
    this.updateBitmap();
    this.updatePosition();
    this.updateVisibility();
};

/* 更新位图 */
Sprite_Timer.prototype.updateBitmap = function() {
    if (this._seconds !== $gameTimer.seconds()) {
        this._seconds = $gameTimer.seconds();
        this.redraw();
    }
};

/* 重绘 */
Sprite_Timer.prototype.redraw = function() {
    var text = this.timerText();
    var width = this.bitmap.width;
    var height = this.bitmap.height;
    this.bitmap.clear();
    this.bitmap.drawText(text, 0, 0, width, height, 'center');
};

/* 计时器文本 */
Sprite_Timer.prototype.timerText = function() {
    var min = Math.floor(this._seconds / 60) % 60;
    var sec = this._seconds % 60;
    return min.padZero(2) + ':' + sec.padZero(2);
};

/* 更新位置 */
Sprite_Timer.prototype.updatePosition = function() {
    this.x = Graphics.width - this.bitmap.width;
    this.y = 0;
};

/* 更新可见性 */
Sprite_Timer.prototype.updateVisibility = function() {
    this.visible = $gameTimer.isWorking();
};

//-----------------------------------------------------------------------------
// 精灵_目的地 
// Sprite_Destination
//
//显示触摸输入的目的地的精灵。 
// The sprite for displaying the destination place of the touch input.

function Sprite_Destination() {
    this.initialize.apply(this, arguments);
}

Sprite_Destination.prototype = Object.create(Sprite.prototype);
Sprite_Destination.prototype.constructor = Sprite_Destination;

/* 初始化 */
Sprite_Destination.prototype.initialize = function() {
    Sprite.prototype.initialize.call(this);
    this.createBitmap();
    this._frameCount = 0;
};

/* 更新 */
Sprite_Destination.prototype.update = function() {
    Sprite.prototype.update.call(this);
    if ($gameTemp.isDestinationValid()){
        this.updatePosition();
        this.updateAnimation();
        this.visible = true;
    } else {
        this._frameCount = 0;
        this.visible = false;
    }
};

/* 创建位图 */
Sprite_Destination.prototype.createBitmap = function() {
    var tileWidth = $gameMap.tileWidth();
    var tileHeight = $gameMap.tileHeight();
    this.bitmap = new Bitmap(tileWidth, tileHeight);
    this.bitmap.fillAll('white');
    this.anchor.x = 0.5;
    this.anchor.y = 0.5;
    this.blendMode = Graphics.BLEND_ADD;
};

/* 更新位置 */
Sprite_Destination.prototype.updatePosition = function() {
    var tileWidth = $gameMap.tileWidth();
    var tileHeight = $gameMap.tileHeight();
    var x = $gameTemp.destinationX();
    var y = $gameTemp.destinationY();
    this.x = ($gameMap.adjustX(x) + 0.5) * tileWidth;
    this.y = ($gameMap.adjustY(y) + 0.5) * tileHeight;
};

/* 更新动画 */
Sprite_Destination.prototype.updateAnimation = function() {
    this._frameCount;
    this._frameCount %= 20;
    this.opacity = (20 - this._frameCount) * 6;
    this.scale.x = 1 + this._frameCount / 20;
    this.scale.y = this.scale.x;
};

//-----------------------------------------------------------------------------
// 精灵组_基础 
// Spriteset_Base
//
// Spriteset_Map 和 Spriteset_Battle 的父类。 
// The superclass of Spriteset_Map and Spriteset_Battle.

function Spriteset_Base() {
    this.initialize.apply(this, arguments);
}

Spriteset_Base.prototype = Object.create(Sprite.prototype);
Spriteset_Base.prototype.constructor = Spriteset_Base;

/* 初始化 */
Spriteset_Base.prototype.initialize = function() {
    Sprite.prototype.initialize.call(this);
    this.setFrame(0, 0, Graphics.width, Graphics.height);
    this._tone = [0, 0, 0, 0];
    this.opaque = true;
    this.createLowerLayer();
    this.createToneChanger();
    this.createUpperLayer();
    this.update();
};

/* 创建下方的图层 */
Spriteset_Base.prototype.createLowerLayer = function() {
    this.createBaseSprite();
};

/* 创建上方的图层 */
Spriteset_Base.prototype.createUpperLayer = function() {
    this.createPictures();
    this.createTimer();
    this.createScreenSprites();
};

/* 更新 */
Spriteset_Base.prototype.update = function() {
    Sprite.prototype.update.call(this);
    this.updateScreenSprites();
    this.updateToneChanger();
    this.updatePosition();
};

/* 更新基础精灵 */
Spriteset_Base.prototype.createBaseSprite = function() {
    this._baseSprite = new Sprite();
    this._baseSprite.setFrame(0, 0, this.width, this.height);
    this._blackScreen = new ScreenSprite();
    this._blackScreen.opacity = 255;
    this.addChild(this._baseSprite);
    this._baseSprite.addChild(this._blackScreen);
};

/* 创建色调变换器 */
Spriteset_Base.prototype.createToneChanger = function() {
    if (Graphics.isWebGL()) {
        this.createWebGLToneChanger();
    } else {
        this.createCanvasToneChanger();
    }
};

/* 创建 WebGL 色调变换器 */
Spriteset_Base.prototype.createWebGLToneChanger = function() {
    var margin = 48;
    var width = Graphics.width + margin * 2;
    var height = Graphics.height + margin * 2;
    this._toneFilter = new ToneFilter();
    this._baseSprite.filters = [this._toneFilter];
    this._baseSprite.filterArea = new Rectangle(-margin, -margin, width, height);
};

/* 创建 Canvas 色调变换器 */
Spriteset_Base.prototype.createCanvasToneChanger = function() {
    this._toneSprite = new ToneSprite();
    this.addChild(this._toneSprite);
};

/* 创建图片 */
Spriteset_Base.prototype.createPictures = function() {
    var width = Graphics.boxWidth;
    var height = Graphics.boxHeight;
    var x = (Graphics.width - width) / 2;
    var y = (Graphics.height - height) / 2;
    this._pictureContainer = new Sprite();
    this._pictureContainer.setFrame(x, y, width, height);
    for (var i = 1; i &lt;= $gameScreen.maxPictures(); i) {
        this._pictureContainer.addChild(new Sprite_Picture(i));
    }
    this.addChild(this._pictureContainer);
};

/* 创建计时器 */
Spriteset_Base.prototype.createTimer = function() {
    this._timerSprite = new Sprite_Timer();
    this.addChild(this._timerSprite);
};

/* 创建画面精灵 
 * 闪烁和渐变效果的两个精灵。
 */
Spriteset_Base.prototype.createScreenSprites = function() {
    this._flashSprite = new ScreenSprite();
    this._fadeSprite = new ScreenSprite();
    this.addChild(this._flashSprite);
    this.addChild(this._fadeSprite);
};

/* 更新画面精灵 */
Spriteset_Base.prototype.updateScreenSprites = function() {
    var color = $gameScreen.flashColor();
    this._flashSprite.setColor(color[0], color[1], color[2]);
    this._flashSprite.opacity = color[3];
    this._fadeSprite.opacity = 255 - $gameScreen.brightness();
};

/* 更新色调变换器 */
Spriteset_Base.prototype.updateToneChanger = function() {
    var tone = $gameScreen.tone();
    if (!this._tone.equals(tone)) {
        this._tone = tone.clone();
        if (Graphics.isWebGL()) {
            this.updateWebGLToneChanger();
        } else {
            this.updateCanvasToneChanger();
        }
    }
};

/* 更新 WebGL 色调变换器 */
Spriteset_Base.prototype.updateWebGLToneChanger = function() {
    var tone = this._tone;
    this._toneFilter.reset();
    this._toneFilter.adjustTone(tone[0], tone[1], tone[2]);
    this._toneFilter.adjustSaturation(-tone[3]);
};

/* 更新 Canvas 色调变换器 */
Spriteset_Base.prototype.updateCanvasToneChanger = function() {
    var tone = this._tone;
    this._toneSprite.setTone(tone[0], tone[1], tone[2], tone[3]);
};

/* 更新位置 */
Spriteset_Base.prototype.updatePosition = function() {
    var screen = $gameScreen;
    var scale = screen.zoomScale();
    this.scale.x = scale;
    this.scale.y = scale;
    this.x = Math.round(-screen.zoomX() * (scale - 1));
    this.y = Math.round(-screen.zoomY() * (scale - 1));
    this.x += Math.round(screen.shake());
};

//-----------------------------------------------------------------------------
// 精灵组_地图 
// Spriteset_Map
//
// 地图画面上的一组精灵。 
// The set of sprites on the map screen.

function Spriteset_Map() {
    this.initialize.apply(this, arguments);
}

Spriteset_Map.prototype = Object.create(Spriteset_Base.prototype);
Spriteset_Map.prototype.constructor = Spriteset_Map;

/* 初始化 */
Spriteset_Map.prototype.initialize = function() {
    Spriteset_Base.prototype.initialize.call(this);
};

/* 创建下方的图层 */
Spriteset_Map.prototype.createLowerLayer = function() {
    Spriteset_Base.prototype.createLowerLayer.call(this);
    this.createParallax();
    this.createTilemap();
    this.createCharacters();
    this.createShadow();
    this.createDestination();
    this.createWeather();
};

/* 更新 */
Spriteset_Map.prototype.update = function() {
    Spriteset_Base.prototype.update.call(this);
    this.updateTileset();
    this.updateParallax();
    this.updateTilemap();
    this.updateShadow();
    this.updateWeather();
};

/* 隐藏人物 */
Spriteset_Map.prototype.hideCharacters = function() {
    for (var i = 0; i &lt; this._characterSprites.length; i) {
        var sprite = this._characterSprites[i];
        if (!sprite.isTile()) {
            sprite.hide();
        }
    }
};

/* 创建远景 */
Spriteset_Map.prototype.createParallax = function() {
    this._parallax = new TilingSprite();
    this._parallax.move(0, 0, Graphics.width, Graphics.height);
    this._baseSprite.addChild(this._parallax);
};

/* 创建图块地图 */
Spriteset_Map.prototype.createTilemap = function() {
    if (Graphics.isWebGL()) {
        this._tilemap = new ShaderTilemap();
    } else {
        this._tilemap = new Tilemap();
    }
    this._tilemap.tileWidth = $gameMap.tileWidth();
    this._tilemap.tileHeight = $gameMap.tileHeight();
    this._tilemap.setData($gameMap.width(), $gameMap.height(), $gameMap.data());
    this._tilemap.horizontalWrap = $gameMap.isLoopHorizontal();
    this._tilemap.verticalWrap = $gameMap.isLoopVertical();
    this.loadTileset();
    this._baseSprite.addChild(this._tilemap);
};

/* 加载图块组 */
Spriteset_Map.prototype.loadTileset = function() {
    this._tileset = $gameMap.tileset();
    if (this._tileset) {
        var tilesetNames = this._tileset.tilesetNames;
        for (var i = 0; i &lt; tilesetNames.length; i) {
            this._tilemap.bitmaps[i] = ImageManager.loadTileset(tilesetNames[i]);
        }
        var newTilesetFlags = $gameMap.tilesetFlags();
        this._tilemap.refreshTileset();
        if (!this._tilemap.flags.equals(newTilesetFlags)) {
            this._tilemap.refresh();
        }
        this._tilemap.flags = newTilesetFlags;
    }
};

/* 创建人物 */
Spriteset_Map.prototype.createCharacters = function() {
    this._characterSprites = [];
    $gameMap.events().forEach(function(event) {
        this._characterSprites.push(new Sprite_Character(event));
    }, this);
    $gameMap.vehicles().forEach(function(vehicle) {
        this._characterSprites.push(new Sprite_Character(vehicle));
    }, this);
    $gamePlayer.followers().reverseEach(function(follower) {
        this._characterSprites.push(new Sprite_Character(follower));
    }, this);
    this._characterSprites.push(new Sprite_Character($gamePlayer));
    for (var i = 0; i &lt; this._characterSprites.length; i) {
        this._tilemap.addChild(this._characterSprites[i]);
    }
};

/* 创建影子 */
Spriteset_Map.prototype.createShadow = function() {
    this._shadowSprite = new Sprite();
    this._shadowSprite.bitmap = ImageManager.loadSystem('Shadow1');
    this._shadowSprite.anchor.x = 0.5;
    this._shadowSprite.anchor.y = 1;
    this._shadowSprite.z = 6;
    this._tilemap.addChild(this._shadowSprite);
};

/* 创建目的地 */
Spriteset_Map.prototype.createDestination = function() {
    this._destinationSprite = new Sprite_Destination();
    this._destinationSprite.z = 9;
    this._tilemap.addChild(this._destinationSprite);
};

/* 创建天气 */
Spriteset_Map.prototype.createWeather = function() {
    this._weather = new Weather();
    this.addChild(this._weather);
};

/* 更新图块组 */
Spriteset_Map.prototype.updateTileset = function() {
    if (this._tileset !== $gameMap.tileset()) {
        this.loadTileset();
    }
};

/*
 * 简单修复画布远景图问题，销毁旧视远景图并且重新添加到树中。
 * Simple fix for canvas parallax issue, destroy old parallax and readd to  the tree.
 */
Spriteset_Map.prototype._canvasReAddParallax = function() {
    var index = this._baseSprite.children.indexOf(this._parallax);
    this._baseSprite.removeChild(this._parallax);
    this._parallax = new TilingSprite();
    this._parallax.move(0, 0, Graphics.width, Graphics.height);
    this._parallax.bitmap = ImageManager.loadParallax(this._parallaxName);
    this._baseSprite.addChildAt(this._parallax,index);
};

/* 更新远景 */
Spriteset_Map.prototype.updateParallax = function() {
    if (this._parallaxName !== $gameMap.parallaxName()) {
        this._parallaxName = $gameMap.parallaxName();

        if (this._parallax.bitmap &amp;&amp; Graphics.isWebGL() != true) {
            this._canvasReAddParallax();
        } else {
            this._parallax.bitmap = ImageManager.loadParallax(this._parallaxName);
        }
    }
    if (this._parallax.bitmap) {
        this._parallax.origin.x = $gameMap.parallaxOx();
        this._parallax.origin.y = $gameMap.parallaxOy();
    }
};

/* 更新图块地图 */
Spriteset_Map.prototype.updateTilemap = function() {
    this._tilemap.origin.x = $gameMap.displayX() * $gameMap.tileWidth();
    this._tilemap.origin.y = $gameMap.displayY() * $gameMap.tileHeight();
};

/* 更新影子 */
Spriteset_Map.prototype.updateShadow = function() {
    var airship = $gameMap.airship();
    this._shadowSprite.x = airship.shadowX();
    this._shadowSprite.y = airship.shadowY();
    this._shadowSprite.opacity = airship.shadowOpacity();
};

/* 更新天气 */
Spriteset_Map.prototype.updateWeather = function() {
    this._weather.type = $gameScreen.weatherType();
    this._weather.power = $gameScreen.weatherPower();
    this._weather.origin.x = $gameMap.displayX() * $gameMap.tileWidth();
    this._weather.origin.y = $gameMap.displayY() * $gameMap.tileHeight();
};

//-----------------------------------------------------------------------------
// 精灵组_战斗 
// Spriteset_Battle
//
// 战斗画面上的一组精灵。 
// The set of sprites on the battle screen.

function Spriteset_Battle() {
    this.initialize.apply(this, arguments);
}

Spriteset_Battle.prototype = Object.create(Spriteset_Base.prototype);
Spriteset_Battle.prototype.constructor = Spriteset_Battle;

/* 初始化 */
Spriteset_Battle.prototype.initialize = function() {
    Spriteset_Base.prototype.initialize.call(this);
    this._battlebackLocated = false;
};

/* 创建下方的图层 */
Spriteset_Battle.prototype.createLowerLayer = function() {
    Spriteset_Base.prototype.createLowerLayer.call(this);
    this.createBackground();
    this.createBattleField();
    this.createBattleback();
    this.createEnemies();
    this.createActors();
};

/* 创建背景 */
Spriteset_Battle.prototype.createBackground = function() {
    this._backgroundSprite = new Sprite();
    this._backgroundSprite.bitmap = SceneManager.backgroundBitmap();
    this._baseSprite.addChild(this._backgroundSprite);
};

/* 更新 */
Spriteset_Battle.prototype.update = function() {
    Spriteset_Base.prototype.update.call(this);
    this.updateActors();
    this.updateBattleback();
};

/* 创建战斗场地 */
Spriteset_Battle.prototype.createBattleField = function() {
    var width = Graphics.boxWidth;
    var height = Graphics.boxHeight;
    var x = (Graphics.width - width) / 2;
    var y = (Graphics.height - height) / 2;
    this._battleField = new Sprite();
    this._battleField.setFrame(x, y, width, height);
    this._battleField.x = x;
    this._battleField.y = y;
    this._baseSprite.addChild(this._battleField);
};

/* 创建战斗背景 */
Spriteset_Battle.prototype.createBattleback = function() {
    var margin = 32;
    var x = -this._battleField.x - margin;
    var y = -this._battleField.y - margin;
    var width = Graphics.width + margin * 2;
    var height = Graphics.height + margin * 2;
    this._back1Sprite = new TilingSprite();
    this._back2Sprite = new TilingSprite();
    this._back1Sprite.bitmap = this.battleback1Bitmap();
    this._back2Sprite.bitmap = this.battleback2Bitmap();
    this._back1Sprite.move(x, y, width, height);
    this._back2Sprite.move(x, y, width, height);
    this._battleField.addChild(this._back1Sprite);
    this._battleField.addChild(this._back2Sprite);
};

/* 更新战斗背景 */
Spriteset_Battle.prototype.updateBattleback = function() {
    if (!this._battlebackLocated) {
        this.locateBattleback();
        this._battlebackLocated = true;
    }
};

/* 放置战斗背景 */
Spriteset_Battle.prototype.locateBattleback = function() {
    var width = this._battleField.width;
    var height = this._battleField.height;
    var sprite1 = this._back1Sprite;
    var sprite2 = this._back2Sprite;
    sprite1.origin.x = sprite1.x + (sprite1.bitmap.width - width) / 2;
    sprite2.origin.x = sprite1.y + (sprite2.bitmap.width - width) / 2;
    if ($gameSystem.isSideView()) {
        sprite1.origin.y = sprite1.x + sprite1.bitmap.height - height;
        sprite2.origin.y = sprite1.y + sprite2.bitmap.height - height;
    }
};

/* 战斗背景 1 位图 */
Spriteset_Battle.prototype.battleback1Bitmap = function() {
    return ImageManager.loadBattleback1(this.battleback1Name());
};

/* 战斗背景 2 位图 */
Spriteset_Battle.prototype.battleback2Bitmap = function() {
    return ImageManager.loadBattleback2(this.battleback2Name());
};

/* 战斗背景 1 名称 */
Spriteset_Battle.prototype.battleback1Name = function() {
    if (BattleManager.isBattleTest()) {
        return $dataSystem.battleback1Name;
    } else if ($gameMap.battleback1Name()) {
        return $gameMap.battleback1Name();
    } else if ($gameMap.isOverworld()) {
        return this.overworldBattleback1Name();
    } else {
        return '';
    }
};

/* 战斗背景 2 名称 */
Spriteset_Battle.prototype.battleback2Name = function() {
    if (BattleManager.isBattleTest()) {
        return $dataSystem.battleback2Name;
    } else if ($gameMap.battleback2Name()) {
        return $gameMap.battleback2Name();
    } else if ($gameMap.isOverworld()) {
        return this.overworldBattleback2Name();
    } else {
        return '';
    }
};

/* 主世界战斗背景 1 名称 */
Spriteset_Battle.prototype.overworldBattleback1Name = function() {
    if ($gameMap.battleback1Name() === '') return '';
    if ($gamePlayer.isInVehicle()) {
        return this.shipBattleback1Name();
    } else {
        return this.normalBattleback1Name();
    }
};

/* 主世界战斗背景 2 名称 */
Spriteset_Battle.prototype.overworldBattleback2Name = function() {
    if ($gameMap.battleback2Name() === '') return '';
    if ($gamePlayer.isInVehicle()) {
        return this.shipBattleback2Name();
    } else {
        return this.normalBattleback2Name();
    }
};

/* 普通战斗背景 1 名称 */
Spriteset_Battle.prototype.normalBattleback1Name = function() {
    return (this.terrainBattleback1Name(this.autotileType(1)) ||
            this.terrainBattleback1Name(this.autotileType(0)) ||
            this.defaultBattleback1Name());
};

/* 普通战斗背景 2 名称 */
Spriteset_Battle.prototype.normalBattleback2Name = function() {
    return (this.terrainBattleback2Name(this.autotileType(1)) ||
            this.terrainBattleback2Name(this.autotileType(0)) ||
            this.defaultBattleback2Name());
};

/* 地形战斗背景 1 名称 */
Spriteset_Battle.prototype.terrainBattleback1Name = function(type) {
    switch (type) {
    case 24: case 25:
        return 'Wasteland';
    case 26: case 27:
        return 'DirtField';
    case 32: case 33:
        return 'Desert';
    case 34:
        return 'Lava1';
    case 35:
        return 'Lava2';
    case 40: case 41:
        return 'Snowfield';
    case 42:
        return 'Clouds';
    case 4: case 5:
        return 'PoisonSwamp';
    default:
        return null;
    }
};

/* 地形战斗背景 2 名称 */
Spriteset_Battle.prototype.terrainBattleback2Name = function(type) {
    switch (type) {
    case 20: case 21:
        return 'Forest';
    case 22: case 30: case 38:
        return 'Cliff';
    case 24: case 25: case 26: case 27:
        return 'Wasteland';
    case 32: case 33:
        return 'Desert';
    case 34: case 35:
        return 'Lava';
    case 40: case 41:
        return 'Snowfield';
    case 42:
        return 'Clouds';
    case 4: case 5:
        return 'PoisonSwamp';
    }
};

/* 默认战斗背景 1 名称 */
Spriteset_Battle.prototype.defaultBattleback1Name = function() {
    return 'Grassland';
};

/* 默认战斗背景 2 名称 */
Spriteset_Battle.prototype.defaultBattleback2Name = function() {
    return 'Grassland';
};

/* 飞艇战斗背景 1 名称 */
Spriteset_Battle.prototype.shipBattleback1Name = function() {
    return 'Ship';
};

/* 飞艇战斗背景 2 名称 */
Spriteset_Battle.prototype.shipBattleback2Name = function() {
    return 'Ship';
};

/* 自动图块类型 */
Spriteset_Battle.prototype.autotileType = function(z) {
    return $gameMap.autotileType($gamePlayer.x, $gamePlayer.y, z);
};

/* 创建敌人 */
Spriteset_Battle.prototype.createEnemies = function() {
    var enemies = $gameTroop.members();
    var sprites = [];
    for (var i = 0; i &lt; enemies.length; i) {
        sprites[i] = new Sprite_Enemy(enemies[i]);
    }
    sprites.sort(this.compareEnemySprite.bind(this));
    for (var j = 0; j &lt; sprites.length; j) {
        this._battleField.addChild(sprites[j]);
    }
    this._enemySprites = sprites;
};

/* 比较敌人精灵 
 * 排序用，坐标 Y 越大越前面，当坐标 Y 一样时则精灵 ID 越大越前面。 
 */
Spriteset_Battle.prototype.compareEnemySprite = function(a, b) {
    if (a.y !== b.y) {
        return a.y - b.y;
    } else {
        return b.spriteId - a.spriteId;
    }
};

/* 创建角色 */
Spriteset_Battle.prototype.createActors = function() {
    this._actorSprites = [];
    for (var i = 0; i &lt; $gameParty.maxBattleMembers(); i) {
        this._actorSprites[i] = new Sprite_Actor();
        this._battleField.addChild(this._actorSprites[i]);
    }
};

/* 更新角色 */
Spriteset_Battle.prototype.updateActors = function() {
    var members = $gameParty.battleMembers();
    for (var i = 0; i &lt; this._actorSprites.length; i+) {
        this._actorSprites[i].setBattler(members[i]);
    }
};

/* 战斗精灵 */
Spriteset_Battle.prototype.battlerSprites = function() {
    return this._enemySprites.concat(this._actorSprites);
};

/* 是否动画播放中 */
Spriteset_Battle.prototype.isAnimationPlaying = function() {
    return this.battlerSprites().some(function(sprite) {
        return sprite.isAnimationPlaying();
    });
};

/* 是否效果中 */
Spriteset_Battle.prototype.isEffecting = function() {
    return this.battlerSprites().some(function(sprite) {
        return sprite.isEffecting();
    });
};

/* 是否有人在移动中 */
Spriteset_Battle.prototype.isAnyoneMoving = function() {
    return this.battlerSprites().some(function(sprite) {
        return sprite.isMoving();
    });
};

/* 是否繁忙 */
Spriteset_Battle.prototype.isBusy = function() {
    return this.isAnimationPlaying() || this.isAnyoneMoving();
};</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_窗口_rpg_windows_js">窗口: rpg_windows.js</h2>
<div class="sectionbody">
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Window_Base: 窗口_基础</p>
</li>
<li>
<p>Window_Selectable: 窗口_可选择</p>
</li>
<li>
<p>Window_Command: 窗口_指令</p>
</li>
<li>
<p>Window_HorzCommand: 窗口_水平指令</p>
</li>
<li>
<p>Window_Help: 窗口_帮助</p>
</li>
<li>
<p>Window_Gold: 窗口_金钱</p>
</li>
<li>
<p>Window_MenuCommand: 窗口_菜单指令</p>
</li>
<li>
<p>Window_MenuStatus: 窗口_菜单状态</p>
</li>
<li>
<p>Window_MenuActor: 窗口_菜单角色</p>
</li>
<li>
<p>Window_ItemCategory: 窗口_物品类型</p>
</li>
<li>
<p>Window_ItemList: 窗口_物品列表</p>
</li>
<li>
<p>Window_SkillType: 窗口技能类型</p>
</li>
<li>
<p>Window_SkillStatus: 窗口_技能状态</p>
</li>
<li>
<p>Window_SkillList: 窗口_技能列表</p>
</li>
<li>
<p>Window_EquipStatus: 窗口_装备状态</p>
</li>
<li>
<p>Window_EquipCommand: 窗口_装备指令</p>
</li>
<li>
<p>Window_EquipSlot: 窗口_装备槽</p>
</li>
<li>
<p>Window_EquipItem: 窗口_装备物品</p>
</li>
<li>
<p>Window_Status: 窗口_状态</p>
</li>
<li>
<p>Window_Options: 窗口_设置</p>
</li>
<li>
<p>Window_SavefileList: 窗口_存档列表</p>
</li>
<li>
<p>Window_ShopCommand: 窗口_商店指令</p>
</li>
<li>
<p>Window_ShopBuy: 窗口_商店购买</p>
</li>
<li>
<p>Window_ShopSell: 窗口_商店出售</p>
</li>
<li>
<p>Window_ShopNumber: 窗口_商店数值</p>
</li>
<li>
<p>Window_ShopStatus: 窗口_商店状态</p>
</li>
<li>
<p>Window_NameEdit: 窗口_名字编辑</p>
</li>
<li>
<p>Window_NameInput: 窗口_名字输入</p>
</li>
<li>
<p>Window_ChoiceList: 窗口_选项列表</p>
</li>
<li>
<p>Window_NumberInput: 窗口_数值输入</p>
</li>
<li>
<p>Window_EventItem: 窗口_事件物品</p>
</li>
<li>
<p>Window_Message: 窗口_信息</p>
</li>
<li>
<p>Window_ScrollText: 窗口_滚动文本</p>
</li>
<li>
<p>Window_MapName: 窗口_地图名字</p>
</li>
<li>
<p>Window_BattleLog: 窗口_战斗日志</p>
</li>
<li>
<p>Window_PartyCommand: 窗口_队伍指令</p>
</li>
<li>
<p>Window_ActorCommand: 窗口_角色指令</p>
</li>
<li>
<p>Window_BattleStatus: 窗口_战斗状态</p>
</li>
<li>
<p>Window_BattleActor: 窗口_战斗角色</p>
</li>
<li>
<p>Window_BattleEnemy: 窗口_战斗敌人</p>
</li>
<li>
<p>Window_BattleSkill: 窗口_战斗技能</p>
</li>
<li>
<p>Window_BattleItem: 窗口_战斗物品</p>
</li>
<li>
<p>Window_TitleCommand: 窗口_标题指令</p>
</li>
<li>
<p>Window_GameEnd: 窗口_游戏结束</p>
</li>
<li>
<p>Window_DebugRange: 窗口_调试范围</p>
</li>
<li>
<p>Window_DebugEdit: 窗口_调试编辑</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-javascript" data-lang="javascript">//=============================================================================
// rpg_windows.js v1.6.1
//=============================================================================

//-----------------------------------------------------------------------------
// 窗口_基础 
// Window_Base
//
// 游戏中所有窗口的父类。 
// The superclass of all windows within the game.

function Window_Base() {
    this.initialize.apply(this, arguments);
}

Window_Base.prototype = Object.create(Window.prototype);
Window_Base.prototype.constructor = Window_Base;

/* 初始化 */
Window_Base.prototype.initialize = function(x, y, width, height) {
    Window.prototype.initialize.call(this);
    this.loadWindowskin();
    this.move(x, y, width, height);
    this.updatePadding();
    this.updateBackOpacity();
    this.updateTone();
    this.createContents();
    this._opening = false;
    this._closing = false;
    this._dimmerSprite = null;
};

Window_Base._iconWidth  = 32;  // 图标宽度 
Window_Base._iconHeight = 32;  // 图标高度 
Window_Base._faceWidth  = 144; // 脸图宽度 
Window_Base._faceHeight = 144; // 脸图高度 

/* 行高度 
 * 菜单每一个选项的高度 
 */
Window_Base.prototype.lineHeight = function() {
    return 36;
};

/* 标准字体 */
Window_Base.prototype.standardFontFace = function() {
    if ($gameSystem.isChinese()) {
        return 'SimHei, Heiti TC, sans-serif';
    } else if ($gameSystem.isKorean()) {
        return 'Dotum, AppleGothic, sans-serif';
    } else {
        return 'GameFont';
    }
};

/* 标准字体大小 */
Window_Base.prototype.standardFontSize = function() {
    return 28;
};

/* 标准填充（内边距） 
 * 内容与背景上下左右四边的距离 
 */
Window_Base.prototype.standardPadding = function() {
    return 18;
};

/* 文本填充（内边距） 
 * 文本与内容左右两边的距离
 */
Window_Base.prototype.textPadding = function() {
    return 6;
};

/* 标准背景不透明度 */
Window_Base.prototype.standardBackOpacity = function() {
    return 192;
};

/* 读取窗口皮肤 */
Window_Base.prototype.loadWindowskin = function() {
    this.windowskin = ImageManager.loadSystem('Window');
};

/* 更新填充（内边距） */
Window_Base.prototype.updatePadding = function() {
    this.padding = this.standardPadding();
};

/* 更新背景不透明度 */
Window_Base.prototype.updateBackOpacity = function() {
    this.backOpacity = this.standardBackOpacity();
};

/* 内容宽度 */
Window_Base.prototype.contentsWidth = function() {
    return this.width - this.standardPadding() * 2;
};

/* 内容高度 */
Window_Base.prototype.contentsHeight = function() {
    return this.height - this.standardPadding() * 2;
};

/* 合适的高度 */
Window_Base.prototype.fittingHeight = function(numLines) {
    return numLines * this.lineHeight() + this.standardPadding() * 2;
};

/* 更新色调 */
Window_Base.prototype.updateTone = function() {
    var tone = $gameSystem.windowTone();
    this.setTone(tone[0], tone[1], tone[2]);
};

/* 创建内容 */
Window_Base.prototype.createContents = function() {
    this.contents = new Bitmap(this.contentsWidth(), this.contentsHeight());
    this.resetFontSettings();
};

/* 重设字体设置 */
Window_Base.prototype.resetFontSettings = function() {
    this.contents.fontFace = this.standardFontFace();
    this.contents.fontSize = this.standardFontSize();
    this.resetTextColor();
};

/* 重设字体颜色 */
Window_Base.prototype.resetTextColor = function() {
    this.changeTextColor(this.normalColor());
};

/* 更新 */
Window_Base.prototype.update = function() {
    Window.prototype.update.call(this);
    this.updateTone();
    this.updateOpen();
    this.updateClose();
    this.updateBackgroundDimmer();
};

/* 更新打开 */
Window_Base.prototype.updateOpen = function() {
    if (this._opening) {
        this.openness = 32;
        if (this.isOpen()) {
            this._opening = false;
        }
    }
};

/* 更新关闭 */
Window_Base.prototype.updateClose = function() {
    if (this._closing) {
        this.openness -= 32;
        if (this.isClosed()) {
            this._closing = false;
        }
    }
};

/* 打开 */
Window_Base.prototype.open = function() {
    if (!this.isOpen()) {
        this._opening = true;
    }
    this._closing = false;
};

/* 关闭 */
Window_Base.prototype.close = function() {
    if (!this.isClosed()) {
        this._closing = true;
    }
    this._opening = false;
};

/* 是否打开中 */
Window_Base.prototype.isOpening = function() {
    return this._opening;
};

/* 是否关闭中 */
Window_Base.prototype.isClosing = function() {
    return this._closing;
};

/* 显示 */
Window_Base.prototype.show = function() {
    this.visible = true;
};

/* 隐藏 */
Window_Base.prototype.hide = function() {
    this.visible = false;
};

/* 活动 */
Window_Base.prototype.activate = function() {
    this.active = true;
};

/* 不活动 */
Window_Base.prototype.deactivate = function() {
    this.active = false;
};

/* 文本颜色 */
Window_Base.prototype.textColor = function(n) {
    var px = 96 + (n % 8) * 12 + 6;
    var py = 144 + Math.floor(n / 8) * 12 + 6;
    return this.windowskin.getPixel(px, py);
};

/* 普通颜色 */
Window_Base.prototype.normalColor = function() {
    return this.textColor(0);
};

/* 系统颜色 */
Window_Base.prototype.systemColor = function() {
    return this.textColor(16);
};

/* 危机颜色 */
Window_Base.prototype.crisisColor = function() {
    return this.textColor(17);
};

/* 死亡颜色 */
Window_Base.prototype.deathColor = function() {
    return this.textColor(18);
};

/* 计量条背景颜色 */
Window_Base.prototype.gaugeBackColor = function() {
    return this.textColor(19);
};

/* HP 计量条颜色 1 */
Window_Base.prototype.hpGaugeColor1 = function() {
    return this.textColor(20);
};

/* HP 计量条颜色 2 */
Window_Base.prototype.hpGaugeColor2 = function() {
    return this.textColor(21);
};

/* MP 计量条颜色 1 */
Window_Base.prototype.mpGaugeColor1 = function() {
    return this.textColor(22);
};

/* MP 计量条颜色 1 */
Window_Base.prototype.mpGaugeColor2 = function() {
    return this.textColor(23);
};

/* MP 消耗颜色 */
Window_Base.prototype.mpCostColor = function() {
    return this.textColor(23);
};

/* 能力上升颜色 
 * 这里指选中的装备与身上装备高对比能力值时上升的颜色
 */
Window_Base.prototype.powerUpColor = function() {
    return this.textColor(24);
};

/* 能力下降颜色 
 * 这里指选中的装备与身上装备高对比能力值时下降的颜色
 */
Window_Base.prototype.powerDownColor = function() {
    return this.textColor(25);
};

/* TP计量条颜色1 */
Window_Base.prototype.tpGaugeColor1 = function() {
    return this.textColor(28);
};

/* TP计量条颜色2 */
Window_Base.prototype.tpGaugeColor2 = function() {
    return this.textColor(29);
};

/* TP消耗颜色 */
Window_Base.prototype.tpCostColor = function() {
    return this.textColor(29);
};

/* 待定颜色（选中选项的那个背景框） */
Window_Base.prototype.pendingColor = function() {
    return this.windowskin.getPixel(120, 120);
};

/* 半透明的不透明度 */
Window_Base.prototype.translucentOpacity = function() {
    return 160;
};

/* 改变文本颜色 */
Window_Base.prototype.changeTextColor = function(color) {
    this.contents.textColor = color;
};

/* 改变绘制不透明度 
 * @param {Boolean} enabled 指令是否启用 
 */
Window_Base.prototype.changePaintOpacity = function(enabled) {
    this.contents.paintOpacity = enabled ? 255 : this.translucentOpacity();
};

/* 绘制文本 */
Window_Base.prototype.drawText = function(text, x, y, maxWidth, align) {
    this.contents.drawText(text, x, y, maxWidth, this.lineHeight(), align);
};

/* 文本宽度 */
Window_Base.prototype.textWidth = function(text) {
    return this.contents.measureTextWidth(text);
};

/* 绘制文本（扩展） */
Window_Base.prototype.drawTextEx = function(text, x, y) {
    if (text) {
        var textState = { index: 0, x: x, y: y, left: x };
        textState.text = this.convertEscapeCharacters(text);
        textState.height = this.calcTextHeight(textState, false);
        this.resetFontSettings();
        while (textState.index &lt; textState.text.length) {
            this.processCharacter(textState);
        }
        return textState.x - x;
    } else {
        return 0;
    }
};

/* 转换转义字符 */
Window_Base.prototype.convertEscapeCharacters = function(text) {
    // \ 替换为 \x1b（ASCII 表对应的是转义符 ESC） 
    text = text.replace(/\\/g, '\x1b');
    // \\ 替换为反斜杠字符 
    text = text.replace(/\x1b\x1b/g, '\\');
    // \V[n] 替换为第 n 个变量的值 
    text = text.replace(/\x1bV\[(\d)\]/gi, function() {
        return $gameVariables.value(parseInt(arguments[1]));
    }.bind(this));
    // \V[n] 替换为第 n 个变量的值 
    text = text.replace(/\x1bV\[(\d+)\]/gi, function() {
        return $gameVariables.value(parseInt(arguments[1]));
    }.bind(this));
    // \N[n] 替换为第 n 个角色的名字 
    text = text.replace(/\x1bN\[(\d+)\]/gi, function() {
        return this.actorName(parseInt(arguments[1]));
    }.bind(this));
    // \P[n] 替换为第 n 个队伍成员 
    text = text.replace(/\x1bP\[(\d+)\]/gi, function() {
        return this.partyMemberName(parseInt(arguments[1]));
    }.bind(this));
    // \G 替换为货币单位 
    text = text.replace(/\x1bG/gi, TextManager.currencyUnit);
    return text;
};

/* 角色名称 */
Window_Base.prototype.actorName = function(n) {
    var actor = n &gt;= 1 ? $gameActors.actor(n) : null;
    return actor ? actor.name() : '';
};

/* 队伍成员名称 */
Window_Base.prototype.partyMemberName = function(n) {
    var actor = n &gt;= 1 ? $gameParty.members()[n - 1] : null;
    return actor ? actor.name() : '';
};

/* 处理字符 */
Window_Base.prototype.processCharacter = function(textState) {
    switch (textState.text[textState.index]) {
    case '\n':
        this.processNewLine(textState);
        break;
    case '\f':
        this.processNewPage(textState);
        break;
    case '\x1b':
        this.processEscapeCharacter(this.obtainEscapeCode(textState), textState);
        break;
    default:
        this.processNormalCharacter(textState);
        break;
    }
};

/* 处理普通字符 */
Window_Base.prototype.processNormalCharacter = function(textState) {
    var c = textState.text[textState.index];
    var w = this.textWidth(c);
    this.contents.drawText(c, textState.x, textState.y, w * 2, textState.height);
    textState.x += w;
};

/* 处理新行 */
Window_Base.prototype.processNewLine = function(textState) {
    textState.x = textState.left;
    textState.y += textState.height;
    textState.height = this.calcTextHeight(textState, false);
    textState.index;
};

/* 处理新页 */
Window_Base.prototype.processNewPage = function(textState) {
    textState.index;
};

/* 获取转义码 */
Window_Base.prototype.obtainEscapeCode = function(textState) {
    textState.index;
    // 匹配开头是 $ . | ^ ! &gt; &lt; { } \ 或 1 个或多个字母（不区分大小写） 
    var regExp = /^[\$\.\|\^!&gt;&lt;\{\}\\]|^<span class="A-Z">/i;
    var arr = regExp.exec(textState.text.slice(textState.index));
    if (arr) {
        textState.index += arr[0].length;
        return arr[0].toUpperCase();
    } else {
        return '';
    }
};

/* 获取转义参数 */
Window_Base.prototype.obtainEscapeParam = function(textState) {
    var arr = /^\[\d</span>\]/.exec(textState.text.slice(textState.index));
    if (arr) {
        textState.index = arr[0].length;
        return parseInt(arr[0].slice(1));
    } else {
        return '';
    }
};

/* 处理转义符 */
Window_Base.prototype.processEscapeCharacter = function(code, textState) {
    switch (code) {
    case 'C':
        this.changeTextColor(this.textColor(this.obtainEscapeParam(textState)));
        break;
    case 'I':
        this.processDrawIcon(this.obtainEscapeParam(textState), textState);
        break;
    case '{':
        this.makeFontBigger();
        break;
    case '}':
        this.makeFontSmaller();
        break;
    }
};

/* 处理绘制图标 */
Window_Base.prototype.processDrawIcon = function(iconIndex, textState) {
    this.drawIcon(iconIndex, textState.x + 2, textState.y + 2);
    textState.x += Window_Base._iconWidth + 4;
};

/* 使字体更大 */
Window_Base.prototype.makeFontBigger = function() {
    if (this.contents.fontSize &lt;= 96) {
        this.contents.fontSize += 12;
    }
};

/* 使字体更小 */
Window_Base.prototype.makeFontSmaller = function() {
    if (this.contents.fontSize &gt;= 24) {
        this.contents.fontSize -= 12;
    }
};

/* 计算文本高度 */
Window_Base.prototype.calcTextHeight = function(textState, all) {
    var lastFontSize = this.contents.fontSize;
    var textHeight = 0;
    var lines = textState.text.slice(textState.index).split('\n');
    var maxLines = all ? lines.length : 1;

    for (var i = 0; i &lt; maxLines; i) {
        var maxFontSize = this.contents.fontSize;
        var regExp = /\x1b[\{\}]/g;
        for (;;) {
            var array = regExp.exec(lines[i]);
            if (array) {
                if (array[0] === '\x1b{') {
                    this.makeFontBigger();
                }
                if (array[0] === '\x1b}') {
                    this.makeFontSmaller();
                }
                if (maxFontSize &lt; this.contents.fontSize) {
                    maxFontSize = this.contents.fontSize;
                }
            } else {
                break;
            }
        }
        textHeight += maxFontSize + 8;
    }

    this.contents.fontSize = lastFontSize;
    return textHeight;
};

/* 绘制图标 */
Window_Base.prototype.drawIcon = function(iconIndex, x, y) {
    var bitmap = ImageManager.loadSystem('IconSet');
    var pw = Window_Base._iconWidth;
    var ph = Window_Base._iconHeight;
    var sx = iconIndex % 16 * pw;
    var sy = Math.floor(iconIndex / 16) * ph;
    this.contents.blt(bitmap, sx, sy, pw, ph, x, y);
};

/* 绘制脸图 
 * 当长宽小于脸图长宽时，截取脸图中间部分；当长宽大于脸图长宽时，脸图居中显示。 
 */
Window_Base.prototype.drawFace = function(faceName, faceIndex, x, y, width, height) {
    width = width || Window_Base._faceWidth;
    height = height || Window_Base._faceHeight;
    var bitmap = ImageManager.loadFace(faceName);
    var pw = Window_Base._faceWidth;
    var ph = Window_Base._faceHeight;
    var sw = Math.min(width, pw);
    var sh = Math.min(height, ph);
    var dx = Math.floor(x + Math.max(width - pw, 0) / 2);
    var dy = Math.floor(y + Math.max(height - ph, 0) / 2);
    var sx = faceIndex % 4 * pw + (pw - sw) / 2;
    var sy = Math.floor(faceIndex / 4) * ph + (ph - sh) / 2;
    this.contents.blt(bitmap, sx, sy, sw, sh, dx, dy);
};
/* 绘制人物 
 * 人物行走图的正面朝向的图，例如存档界面里绘制的人物图。 
 */
Window_Base.prototype.drawCharacter = function(characterName, characterIndex, x, y) {
    var bitmap = ImageManager.loadCharacter(characterName);
    var big = ImageManager.isBigCharacter(characterName);
    var pw = bitmap.width / (big ? 3 : 12);
    var ph = bitmap.height / (big ? 4 : 8);
    var n = characterIndex;
    var sx = (n % 4 * 3 + 1) * pw;
    var sy = (Math.floor(n / 4) * 4) * ph;
    this.contents.blt(bitmap, sx, sy, pw, ph, x - pw / 2, y - ph);
};

/* 绘制计量条（HP、MP、TP的计量条） */
Window_Base.prototype.drawGauge = function(x, y, width, rate, color1, color2) {
    var fillW = Math.floor(width * rate);
    var gaugeY = y + this.lineHeight() - 8;
    this.contents.fillRect(x, gaugeY, width, 6, this.gaugeBackColor());
    this.contents.gradientFillRect(x, gaugeY, fillW, 6, color1, color2);
};

/* HP 颜色 
 * 普通、频死、死亡三种状态下HP的数值的颜色不同。 
 */
Window_Base.prototype.hpColor = function(actor) {
    if (actor.isDead()) {
        return this.deathColor();
    } else if (actor.isDying()) {
        return this.crisisColor();
    } else {
        return this.normalColor();
    }
};

/* MP 颜色 */
Window_Base.prototype.mpColor = function(actor) {
    return this.normalColor();
};

/* TP 颜色 */
Window_Base.prototype.tpColor = function(actor) {
    return this.normalColor();
};

/* 绘制角色行走图 */
Window_Base.prototype.drawActorCharacter = function(actor, x, y) {
    this.drawCharacter(actor.characterName(), actor.characterIndex(), x, y);
};

/* 绘制角色脸图 */
Window_Base.prototype.drawActorFace = function(actor, x, y, width, height) {
    this.drawFace(actor.faceName(), actor.faceIndex(), x, y, width, height);
};

/* 绘制角色名字 */
Window_Base.prototype.drawActorName = function(actor, x, y, width) {
    width = width || 168;
    this.changeTextColor(this.hpColor(actor));
    this.drawText(actor.name(), x, y, width);
};

/* 绘制角色职业 */
Window_Base.prototype.drawActorClass = function(actor, x, y, width) {
    width = width || 168;
    this.resetTextColor();
    this.drawText(actor.currentClass().name, x, y, width);
};

/* 绘制角色昵称 */
Window_Base.prototype.drawActorNickname = function(actor, x, y, width) {
    width = width || 270;
    this.resetTextColor();
    this.drawText(actor.nickname(), x, y, width);
};

/* 绘制角色等级 */
Window_Base.prototype.drawActorLevel = function(actor, x, y) {
    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.levelA, x, y, 48);
    this.resetTextColor();
    this.drawText(actor.level, x + 84, y, 36, 'right');
};

/* 绘制角色图标（状态的图标，如中毒） */
Window_Base.prototype.drawActorIcons = function(actor, x, y, width) {
    width = width || 144;
    var icons = actor.allIcons().slice(0, Math.floor(width / Window_Base._iconWidth));
    for (var i = 0; i &lt; icons.length; i) {
        this.drawIcon(icons[i], x + Window_Base._iconWidth * i, y + 2);
    }
};

/* 绘制当前值与最大值（HP 和 MP 的值，如 1/100） */
Window_Base.prototype.drawCurrentAndMax = function(current, max, x, y,
                                                   width, color1, color2) {
    var labelWidth = this.textWidth('HP');
    var valueWidth = this.textWidth('0000');
    var slashWidth = this.textWidth('/');
    var x1 = x + width - valueWidth;
    var x2 = x1 - slashWidth;
    var x3 = x2 - valueWidth;
    if (x3 &gt;= x + labelWidth) {
        this.changeTextColor(color1);
        this.drawText(current, x3, y, valueWidth, 'right');
        this.changeTextColor(color2);
        this.drawText('/', x2, y, slashWidth, 'right');
        this.drawText(max, x1, y, valueWidth, 'right');
    } else {
        this.changeTextColor(color1);
        this.drawText(current, x1, y, valueWidth, 'right');
    }
};

/* 绘制角色 HP */
Window_Base.prototype.drawActorHp = function(actor, x, y, width) {
    width = width || 186;
    var color1 = this.hpGaugeColor1();
    var color2 = this.hpGaugeColor2();
    this.drawGauge(x, y, width, actor.hpRate(), color1, color2);
    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.hpA, x, y, 44);
    this.drawCurrentAndMax(actor.hp, actor.mhp, x, y, width,
                           this.hpColor(actor), this.normalColor());
};

/* 绘制角色 MP */
Window_Base.prototype.drawActorMp = function(actor, x, y, width) {
    width = width || 186;
    var color1 = this.mpGaugeColor1();
    var color2 = this.mpGaugeColor2();
    this.drawGauge(x, y, width, actor.mpRate(), color1, color2);
    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.mpA, x, y, 44);
    this.drawCurrentAndMax(actor.mp, actor.mmp, x, y, width,
                           this.mpColor(actor), this.normalColor());
};

/* 绘制角色 TP */
Window_Base.prototype.drawActorTp = function(actor, x, y, width) {
    width = width || 96;
    var color1 = this.tpGaugeColor1();
    var color2 = this.tpGaugeColor2();
    this.drawGauge(x, y, width, actor.tpRate(), color1, color2);
    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.tpA, x, y, 44);
    this.changeTextColor(this.tpColor(actor));
    this.drawText(actor.tp, x + width - 64, y, 64, 'right');
};

/* 绘制角色简单的状态（名字、等级、图标、职业、HP、MP） */
Window_Base.prototype.drawActorSimpleStatus = function(actor, x, y, width) {
    var lineHeight = this.lineHeight();
    var x2 = x + 180;
    var width2 = Math.min(200, width - 180 - this.textPadding());
    this.drawActorName(actor, x, y);
    this.drawActorLevel(actor, x, y + lineHeight * 1);
    this.drawActorIcons(actor, x, y + lineHeight * 2);
    this.drawActorClass(actor, x2, y);
    this.drawActorHp(actor, x2, y + lineHeight * 1, width2);
    this.drawActorMp(actor, x2, y + lineHeight * 2, width2);
};

/* 绘制物品名字 */
Window_Base.prototype.drawItemName = function(item, x, y, width) {
    width = width || 312;
    if (item) {
        var iconBoxWidth = Window_Base._iconWidth + 4;
        this.resetTextColor();
        this.drawIcon(item.iconIndex, x + 2, y + 2);
        this.drawText(item.name, x + iconBoxWidth, y, width - iconBoxWidth);
    }
};

/* 绘制货币值 */
Window_Base.prototype.drawCurrencyValue = function(value, unit, x, y, width) {
    var unitWidth = Math.min(80, this.textWidth(unit));
    this.resetTextColor();
    this.drawText(value, x, y, width - unitWidth - 6, 'right');
    this.changeTextColor(this.systemColor());
    this.drawText(unit, x + width - unitWidth, y, unitWidth, 'right');
};

/* 参数改变文本颜色 
 * 装备界面或商店界面比较装备能力值时会使用
 * @param {Number} change 能力值是否改变（正数：能力值上升颜色，负数：能力值下降颜色，0：能力值不变的普通颜色）
 */
Window_Base.prototype.paramchangeTextColor = function(change) {
    if (change &gt; 0) {
        return this.powerUpColor();
    } else if (change &lt; 0) {
        return this.powerDownColor();
    } else {
        return this.normalColor();
    }
};

/* 设置背景类型 
 * @param {Number} type 类型（0：窗口，1：暗淡，2：透明） 
 */
Window_Base.prototype.setBackgroundType = function(type) {
    if (type === 0) {
        this.opacity = 255;
    } else {
        this.opacity = 0;
    }
    if (type === 1) {
        this.showBackgroundDimmer();
    } else {
        this.hideBackgroundDimmer();
    }
};

/* 设置暗淡背景 */
Window_Base.prototype.showBackgroundDimmer = function() {
    if (!this._dimmerSprite) {
        this._dimmerSprite = new Sprite();
        this._dimmerSprite.bitmap = new Bitmap(0, 0);
        this.addChildToBack(this._dimmerSprite);
    }
    var bitmap = this._dimmerSprite.bitmap;
    if (bitmap.width !== this.width || bitmap.height !== this.height) {
        this.refreshDimmerBitmap();
    }
    this._dimmerSprite.visible = true;
    this.updateBackgroundDimmer();
};

/* 隐藏暗淡背景 */
Window_Base.prototype.hideBackgroundDimmer = function() {
    if (this._dimmerSprite) {
        this._dimmerSprite.visible = false;
    }
};

/* 更新暗淡背景 */
Window_Base.prototype.updateBackgroundDimmer = function() {
    if (this._dimmerSprite) {
        this._dimmerSprite.opacity = this.openness;
    }
};

/* 刷新暗淡位图 */
Window_Base.prototype.refreshDimmerBitmap = function() {
    if (this._dimmerSprite) {
        var bitmap = this._dimmerSprite.bitmap;
        var w = this.width;
        var h = this.height;
        var m = this.padding;
        var c1 = this.dimColor1();
        var c2 = this.dimColor2();
        bitmap.resize(w, h);
        bitmap.gradientFillRect(0, 0, w, m, c2, c1, true);
        bitmap.fillRect(0, m, w, h - m * 2, c1);
        bitmap.gradientFillRect(0, h - m, w, m, c1, c2, true);
        this._dimmerSprite.setFrame(0, 0, w, h);
    }
};

/* 暗淡颜色 1 */
Window_Base.prototype.dimColor1 = function() {
    return 'rgba(0, 0, 0, 0.6)';
};

/* 暗淡颜色 2 */
Window_Base.prototype.dimColor2 = function() {
    return 'rgba(0, 0, 0, 0)';
};

 /* 画布 X 坐标转换到本地 X 坐标 */
Window_Base.prototype.canvasToLocalX = function(x) {
    var node = this;
    while (node) {
        x -= node.x;
        node = node.parent;
    }
    return x;
};

 /* 画布 Y 坐标转换到本地 Y 坐标 */
Window_Base.prototype.canvasToLocalY = function(y) {
    var node = this;
    while (node) {
        y -= node.y;
        node = node.parent;
    }
    return y;
};

/* 储存脸图图像 */
Window_Base.prototype.reserveFaceImages = function() {
    $gameParty.members().forEach(function(actor) {
        ImageManager.reserveFace(actor.faceName());
    }, this);
};

//-----------------------------------------------------------------------------
// 窗口_可选择 
// Window_Selectable
//
// 具有光标移动和滚动功能的窗口类。 
// The window class with cursor movement and scroll functions.

function Window_Selectable() {
    this.initialize.apply(this, arguments);
}

Window_Selectable.prototype = Object.create(Window_Base.prototype);
Window_Selectable.prototype.constructor = Window_Selectable;

/* 初始化 */
Window_Selectable.prototype.initialize = function(x, y, width, height) {
    Window_Base.prototype.initialize.call(this, x, y, width, height);
    this._index = -1;
    this._cursorFixed = false;
    this._cursorAll = false;
    this._stayCount = 0;
    this._helpWindow = null;
    this._handlers = {};
    this._touching = false;
    this._scrollX = 0;
    this._scrollY = 0;
    this.deactivate();
};

/* 索引 */
Window_Selectable.prototype.index = function() {
    return this._index;
};

/* 光标固定 
 * 选中对象，光标固定不再闪烁。 
 */
Window_Selectable.prototype.cursorFixed = function() {
    return this._cursorFixed;
};

/* 设置光标固定 */
Window_Selectable.prototype.setCursorFixed = function(cursorFixed) {
    this._cursorFixed = cursorFixed;
};

/* 光标所有 
 * 选中所有对象。 
 */
Window_Selectable.prototype.cursorAll = function() {
    return this._cursorAll;
};

/* 设置光标所有 */
Window_Selectable.prototype.setCursorAll = function(cursorAll) {
    this._cursorAll = cursorAll;
};

/* 最大列数 */
Window_Selectable.prototype.maxCols = function() {
    return 1;
};

/* 最大项目数 */
Window_Selectable.prototype.maxItems = function() {
    return 0;
};

/* 间隔 */
Window_Selectable.prototype.spacing = function() {
    return 12;
};

/* 项目宽度 */
Window_Selectable.prototype.itemWidth = function() {
    return Math.floor((this.width - this.padding * 2 +
                       this.spacing()) / this.maxCols() - this.spacing());
};

/* 项目高度 */
Window_Selectable.prototype.itemHeight = function() {
    return this.lineHeight();
};

/* 最大行数 */
Window_Selectable.prototype.maxRows = function() {
    return Math.max(Math.ceil(this.maxItems() / this.maxCols()), 1);
};

/* 活动 */
Window_Selectable.prototype.activate = function() {
    Window_Base.prototype.activate.call(this);
    this.reselect();
};

/* 不活动 */
Window_Selectable.prototype.deactivate = function() {
    Window_Base.prototype.deactivate.call(this);
    this.reselect();
};

/* 选择 */
Window_Selectable.prototype.select = function(index) {
    this._index = index;
    this._stayCount = 0;
    this.ensureCursorVisible();
    this.updateCursor();
    this.callUpdateHelp();
};

/* 不选择 */
Window_Selectable.prototype.deselect = function() {
    this.select(-1);
};

/* 重新选择 */
Window_Selectable.prototype.reselect = function() {
    this.select(this._index);
};

/* 行数 */
Window_Selectable.prototype.row = function() {
    return Math.floor(this.index() / this.maxCols());
};

/* 顶部行数 */
Window_Selectable.prototype.topRow = function() {
    return Math.floor(this._scrollY / this.itemHeight());
};

/* 最大顶部行数 */
Window_Selectable.prototype.maxTopRow = function() {
    return Math.max(0, this.maxRows() - this.maxPageRows());
};

/* 设置顶部行数 */
Window_Selectable.prototype.setTopRow = function(row) {
    var scrollY = row.clamp(0, this.maxTopRow()) * this.itemHeight();
    if (this._scrollY !== scrollY) {
        this._scrollY = scrollY;
        this.refresh();
        this.updateCursor();
    }
};

/* 重设滚动 */
Window_Selectable.prototype.resetScroll = function() {
    this.setTopRow(0);
};

/* 最大页面行数 */
Window_Selectable.prototype.maxPageRows = function() {
    var pageHeight = this.height - this.padding * 2;
    return Math.floor(pageHeight / this.itemHeight());
};

/* 最大页面项目数 */
Window_Selectable.prototype.maxPageItems = function() {
    return this.maxPageRows() * this.maxCols();
};

/* 是否横向 */
Window_Selectable.prototype.isHorizontal = function() {
    return this.maxPageRows() === 1;
};

/* 底部行数 */
Window_Selectable.prototype.bottomRow = function() {
    return Math.max(0, this.topRow() + this.maxPageRows() - 1);
};

/* 设置底部行数 */
Window_Selectable.prototype.setBottomRow = function(row) {
    this.setTopRow(row - (this.maxPageRows() - 1));
};

/* 顶部索引 */
Window_Selectable.prototype.topIndex = function() {
    return this.topRow() * this.maxCols();
};

/* 项目矩形区域 */
Window_Selectable.prototype.itemRect = function(index) {
    var rect = new Rectangle();
    var maxCols = this.maxCols();
    rect.width = this.itemWidth();
    rect.height = this.itemHeight();
    rect.x = index % maxCols * (rect.width + this.spacing()) - this._scrollX;
    rect.y = Math.floor(index / maxCols) * rect.height - this._scrollY;
    return rect;
};

/* 关于文本的项目矩形区域 */
Window_Selectable.prototype.itemRectForText = function(index) {
    var rect = this.itemRect(index);
    rect.x += this.textPadding();
    rect.width -= this.textPadding() * 2;
    return rect;
};

/* 设置帮助窗口 */
Window_Selectable.prototype.setHelpWindow = function(helpWindow) {
    this._helpWindow = helpWindow;
    this.callUpdateHelp();
};

/* 显示帮助窗口 */
Window_Selectable.prototype.showHelpWindow = function() {
    if (this._helpWindow) {
        this._helpWindow.show();
    }
};

/* 设隐藏帮助窗口 */
Window_Selectable.prototype.hideHelpWindow = function() {
    if (this._helpWindow) {
        this._helpWindow.hide();
    }
};

/* 设置处理者 */
Window_Selectable.prototype.setHandler = function(symbol, method) {
    this._handlers[symbol] = method;
};

/* 是否有处理者 */
Window_Selectable.prototype.isHandled = function(symbol) {
    return !!this._handlers[symbol];
};

/* 呼叫处理者 */
Window_Selectable.prototype.callHandler = function(symbol) {
    if (this.isHandled(symbol)) {
        this._handlers[symbol]();
    }
};

/* 是否打开并且活动 */
Window_Selectable.prototype.isOpenAndActive = function() {
    return this.isOpen() &amp;&amp; this.active;
};

/* 是否光标可移动 */
Window_Selectable.prototype.isCursorMovable = function() {
    return (this.isOpenAndActive() &amp;&amp; !this._cursorFixed &amp;&amp;
            !this._cursorAll &amp;&amp; this.maxItems() &gt; 0);
};

/* 光标向下 */
Window_Selectable.prototype.cursorDown = function(wrap) {
    var index = this.index();
    var maxItems = this.maxItems();
    var maxCols = this.maxCols();
    if (index &lt; maxItems - maxCols || (wrap &amp;&amp; maxCols === 1)) {
        this.select((index + maxCols) % maxItems);
    }
};

/* 光标向上 */
Window_Selectable.prototype.cursorUp = function(wrap) {
    var index = this.index();
    var maxItems = this.maxItems();
    var maxCols = this.maxCols();
    if (index &gt;= maxCols || (wrap &amp;&amp; maxCols === 1)) {
        this.select((index - maxCols + maxItems) % maxItems);
    }
};

/* 光标向右 */
Window_Selectable.prototype.cursorRight = function(wrap) {
    var index = this.index();
    var maxItems = this.maxItems();
    var maxCols = this.maxCols();
    if (maxCols &gt;= 2 &amp;&amp; (index &lt; maxItems - 1 || (wrap &amp;&amp; this.isHorizontal()))) {
        this.select((index + 1) % maxItems);
    }
};

/* 光标向左 */
Window_Selectable.prototype.cursorLeft = function(wrap) {
    var index = this.index();
    var maxItems = this.maxItems();
    var maxCols = this.maxCols();
    if (maxCols &gt;= 2 &amp;&amp; (index &gt; 0 || (wrap &amp;&amp; this.isHorizontal()))) {
        this.select((index - 1 + maxItems) % maxItems);
    }
};

/* 光标下翻页 */
Window_Selectable.prototype.cursorPagedown = function() {
    var index = this.index();
    var maxItems = this.maxItems();
    if (this.topRow() + this.maxPageRows() &lt; this.maxRows()) {
        this.setTopRow(this.topRow() + this.maxPageRows());
        this.select(Math.min(index + this.maxPageItems(), maxItems - 1));
    }
};

/* 光标上翻页 */
Window_Selectable.prototype.cursorPageup = function() {
    var index = this.index();
    if (this.topRow() &gt; 0) {
        this.setTopRow(this.topRow() - this.maxPageRows());
        this.select(Math.max(index - this.maxPageItems(), 0));
    }
};

/* 滚动向下 */
Window_Selectable.prototype.scrollDown = function() {
    if (this.topRow() + 1 &lt; this.maxRows()) {
        this.setTopRow(this.topRow() + 1);
    }
};

/* 滚动向上 */
Window_Selectable.prototype.scrollUp = function() {
    if (this.topRow() &gt; 0) {
        this.setTopRow(this.topRow() - 1);
    }
};

/* 更新 */
Window_Selectable.prototype.update = function() {
    Window_Base.prototype.update.call(this);
    this.updateArrows();
    this.processCursorMove();
    this.processHandling();
    this.processWheel();
    this.processTouch();
    this._stayCount;
};

/* 更新箭头 */
Window_Selectable.prototype.updateArrows = function() {
    var topRow = this.topRow();
    var maxTopRow = this.maxTopRow();
    this.downArrowVisible = maxTopRow &gt; 0 &amp;&amp; topRow &lt; maxTopRow;
    this.upArrowVisible = topRow &gt; 0;
};

/* 处理光标移动 */
Window_Selectable.prototype.processCursorMove = function() {
    if (this.isCursorMovable()) {
        var lastIndex = this.index();
        if (Input.isRepeated('down')) {
            this.cursorDown(Input.isTriggered('down'));
        }
        if (Input.isRepeated('up')) {
            this.cursorUp(Input.isTriggered('up'));
        }
        if (Input.isRepeated('right')) {
            this.cursorRight(Input.isTriggered('right'));
        }
        if (Input.isRepeated('left')) {
            this.cursorLeft(Input.isTriggered('left'));
        }
        if (!this.isHandled('pagedown') &amp;&amp; Input.isTriggered('pagedown')) {
            this.cursorPagedown();
        }
        if (!this.isHandled('pageup') &amp;&amp; Input.isTriggered('pageup')) {
            this.cursorPageup();
        }
        if (this.index() !== lastIndex) {
            SoundManager.playCursor();
        }
    }
};

/* 处理处理 */
Window_Selectable.prototype.processHandling = function() {
    if (this.isOpenAndActive()) {
        if (this.isOkEnabled() &amp;&amp; this.isOkTriggered()) {
            this.processOk();
        } else if (this.isCancelEnabled() &amp;&amp; this.isCancelTriggered()) {
            this.processCancel();
        } else if (this.isHandled('pagedown') &amp;&amp; Input.isTriggered('pagedown')) {
            this.processPagedown();
        } else if (this.isHandled('pageup') &amp;&amp; Input.isTriggered('pageup')) {
            this.processPageup();
        }
    }
};

/* 处理鼠标滚轮 */
Window_Selectable.prototype.processWheel = function() {
    if (this.isOpenAndActive()) {
        var threshold = 20;
        if (TouchInput.wheelY &gt;= threshold) {
            this.scrollDown();
        }
        if (TouchInput.wheelY &lt;= -threshold) {
            this.scrollUp();
        }
    }
};

/* 处理触摸 */
Window_Selectable.prototype.processTouch = function() {
    if (this.isOpenAndActive()) {
        if (TouchInput.isTriggered() &amp;&amp; this.isTouchedInsideFrame()) {
            this._touching = true;
            this.onTouch(true);
        } else if (TouchInput.isCancelled()) {
            if (this.isCancelEnabled()) {
                this.processCancel();
            }
        }
        if (this._touching) {
            if (TouchInput.isPressed()) {
                this.onTouch(false);
            } else {
                this._touching = false;
            }
        }
    } else {
        this._touching = false;
    }
};

/* 是否触摸在内部框 */
Window_Selectable.prototype.isTouchedInsideFrame = function() {
    var x = this.canvasToLocalX(TouchInput.x);
    var y = this.canvasToLocalY(TouchInput.y);
    return x &gt;= 0 &amp;&amp; y &gt;= 0 &amp;&amp; x &lt; this.width &amp;&amp; y &lt; this.height;
};

/* 当触摸 */
Window_Selectable.prototype.onTouch = function(triggered) {
    var lastIndex = this.index();
    var x = this.canvasToLocalX(TouchInput.x);
    var y = this.canvasToLocalY(TouchInput.y);
    var hitIndex = this.hitTest(x, y);
    if (hitIndex &gt;= 0) {
        if (hitIndex === this.index()) {
            if (triggered &amp;&amp; this.isTouchOkEnabled()) {
                this.processOk();
            }
        } else if (this.isCursorMovable()) {
            this.select(hitIndex);
        }
    } else if (this._stayCount &gt;= 10) {
        if (y &lt; this.padding) {
            this.cursorUp();
        } else if (y &gt;= this.height - this.padding) {
            this.cursorDown();
        }
    }
    if (this.index() !== lastIndex) {
        SoundManager.playCursor();
    }
};

/* 命中测试 
 * 判断点是在哪个项目的矩形区域内，返回该项目索引。 
 */
Window_Selectable.prototype.hitTest = function(x, y) {
    if (this.isContentsArea(x, y)) {
        var cx = x - this.padding;
        var cy = y - this.padding;
        var topIndex = this.topIndex();
        for (var i = 0; i &lt; this.maxPageItems(); i) {
            var index = topIndex + i;
            if (index &lt; this.maxItems()) {
                var rect = this.itemRect(index);
                var right = rect.x + rect.width;
                var bottom = rect.y + rect.height;
                if (cx &gt;= rect.x &amp;&amp; cy &gt;= rect.y &amp;&amp; cx &lt; right &amp;&amp; cy &lt; bottom) {
                    return index;
                }
            }
        }
    }
    return -1;
};

/* 是否内容区域 */
Window_Selectable.prototype.isContentsArea = function(x, y) {
    var left = this.padding;
    var top = this.padding;
    var right = this.width - this.padding;
    var bottom = this.height - this.padding;
    return (x &gt;= left &amp;&amp; y &gt;= top &amp;&amp; x &lt; right &amp;&amp; y &lt; bottom);
};

/* 是否触摸确定启用 */
Window_Selectable.prototype.isTouchOkEnabled = function() {
    return this.isOkEnabled();
};

/* 是否确定启用 */
Window_Selectable.prototype.isOkEnabled = function() {
    return this.isHandled('ok');
};

/* 是否取消启用 */
Window_Selectable.prototype.isCancelEnabled = function() {
    return this.isHandled('cancel');
};

/* 是否确定触发 */
Window_Selectable.prototype.isOkTriggered = function() {
    return Input.isRepeated('ok');
};

/* 是否取消触发 */
Window_Selectable.prototype.isCancelTriggered = function() {
    return Input.isRepeated('cancel');
};

/* 处理确定 */
Window_Selectable.prototype.processOk = function() {
    if (this.isCurrentItemEnabled()) {
        this.playOkSound();
        this.updateInputData();
        this.deactivate();
        this.callOkHandler();
    } else {
        this.playBuzzerSound();
    }
};

/* 播放确定声音 */
Window_Selectable.prototype.playOkSound = function() {
    SoundManager.playOk();
};

/* 播放蜂鸣器声音 */
Window_Selectable.prototype.playBuzzerSound = function() {
    SoundManager.playBuzzer();
};

/* 呼叫确定处理者 */
Window_Selectable.prototype.callOkHandler = function() {
    this.callHandler('ok');
};

/* 处理取消 */
Window_Selectable.prototype.processCancel = function() {
    SoundManager.playCancel();
    this.updateInputData();
    this.deactivate();
    this.callCancelHandler();
};

/* 呼叫取消处理者 */
Window_Selectable.prototype.callCancelHandler = function() {
    this.callHandler('cancel');
};

/* 处理上翻页 */
Window_Selectable.prototype.processPageup = function() {
    SoundManager.playCursor();
    this.updateInputData();
    this.deactivate();
    this.callHandler('pageup');
};

/* 处理下翻页 */
Window_Selectable.prototype.processPagedown = function() {
    SoundManager.playCursor();
    this.updateInputData();
    this.deactivate();
    this.callHandler('pagedown');
};

/* 更新输入数据 */
Window_Selectable.prototype.updateInputData = function() {
    Input.update();
    TouchInput.update();
};

/* 更新光标 */
Window_Selectable.prototype.updateCursor = function() {
    if (this._cursorAll) {
        var allRowsHeight = this.maxRows() * this.itemHeight();
        this.setCursorRect(0, 0, this.contents.width, allRowsHeight);
        this.setTopRow(0);
    } else if (this.isCursorVisible()) {
        var rect = this.itemRect(this.index());
        this.setCursorRect(rect.x, rect.y, rect.width, rect.height);
    } else {
        this.setCursorRect(0, 0, 0, 0);
    }
};

/* 是否光标可见的 */
Window_Selectable.prototype.isCursorVisible = function() {
    var row = this.row();
    return row &gt;= this.topRow() &amp;&amp; row &lt;= this.bottomRow();
};

/* 保证光标可见的 */
Window_Selectable.prototype.ensureCursorVisible = function() {
    var row = this.row();
    if (row &lt; this.topRow()) {
        this.setTopRow(row);
    } else if (row &gt; this.bottomRow()) {
        this.setBottomRow(row);
    }
};

/* 呼叫更新帮助 */
Window_Selectable.prototype.callUpdateHelp = function() {
    if (this.active &amp;&amp; this._helpWindow) {
        this.updateHelp();
    }
};

/* 更新帮助 */
Window_Selectable.prototype.updateHelp = function() {
    this._helpWindow.clear();
};

/* 设置帮助窗口项目 */
Window_Selectable.prototype.setHelpWindowItem = function(item) {
    if (this._helpWindow) {
        this._helpWindow.setItem(item);
    }
};

/* 是否当前项目启用 */
Window_Selectable.prototype.isCurrentItemEnabled = function() {
    return true;
};

/* 绘制所有项目 */
Window_Selectable.prototype.drawAllItems = function() {
    var topIndex = this.topIndex();
    for (var i = 0; i &lt; this.maxPageItems(); i) {
        var index = topIndex + i;
        if (index &lt; this.maxItems()) {
            this.drawItem(index);
        }
    }
};

/* 绘制项目 */
Window_Selectable.prototype.drawItem = function(index) {
};

/* 清除项目 */
Window_Selectable.prototype.clearItem = function(index) {
    var rect = this.itemRect(index);
    this.contents.clearRect(rect.x, rect.y, rect.width, rect.height);
};

/* 重绘项目 */
Window_Selectable.prototype.redrawItem = function(index) {
    if (index &gt;= 0) {
        this.clearItem(index);
        this.drawItem(index);
    }
};

/* 重绘当前项目 */
Window_Selectable.prototype.redrawCurrentItem = function() {
    this.redrawItem(this.index());
};

/* 刷新 */
Window_Selectable.prototype.refresh = function() {
    if (this.contents) {
        this.contents.clear();
        this.drawAllItems();
    }
};

//-----------------------------------------------------------------------------
// 窗口_指令 
// Window_Command
//
// 选择指令的窗口的父类。 
// The superclass of windows for selecting a command.

function Window_Command() {
    this.initialize.apply(this, arguments);
}

Window_Command.prototype = Object.create(Window_Selectable.prototype);
Window_Command.prototype.constructor = Window_Command;

/* 初始化 */
Window_Command.prototype.initialize = function(x, y) {
    this.clearCommandList();
    this.makeCommandList();
    var width = this.windowWidth();
    var height = this.windowHeight();
    Window_Selectable.prototype.initialize.call(this, x, y, width, height);
    this.refresh();
    this.select(0);
    this.activate();
};

/* 窗口宽度 */
Window_Command.prototype.windowWidth = function() {
    return 240;
};

/* 窗口高度 */
Window_Command.prototype.windowHeight = function() {
    return this.fittingHeight(this.numVisibleRows());
};

/* 可见的行数 */
Window_Command.prototype.numVisibleRows = function() {
    return Math.ceil(this.maxItems() / this.maxCols());
};

/* 最大项目数 */
Window_Command.prototype.maxItems = function() {
    return this._list.length;
};

/* 清空指令列表 */
Window_Command.prototype.clearCommandList = function() {
    this._list = [];
};

/* 制作指令列表 */
Window_Command.prototype.makeCommandList = function() {
};

/* 增加指令 */
Window_Command.prototype.addCommand = function(name, symbol, enabled, ext) {
    if (enabled === undefined) {
        enabled = true;
    }
    if (ext === undefined) {
        ext = null;
    }
    this._list.push({ name: name, symbol: symbol, enabled: enabled, ext: ext});
};

/* 指令名字 */
Window_Command.prototype.commandName = function(index) {
    return this._list[index].name;
};

/* 指令标识 */
Window_Command.prototype.commandSymbol = function(index) {
    return this._list[index].symbol;
};

/* 是否指令启用 */
Window_Command.prototype.isCommandEnabled = function(index) {
    return this._list[index].enabled;
};

/* 当前数据 */
Window_Command.prototype.currentData = function() {
    return this.index() &gt;= 0 ? this._list[this.index()] : null;
};

/* 是否当前项目启用 */
Window_Command.prototype.isCurrentItemEnabled = function() {
    return this.currentData() ? this.currentData().enabled : false;
};

/* 当前标识 */
Window_Command.prototype.currentSymbol = function() {
    return this.currentData() ? this.currentData().symbol : null;
};

/* 当前扩展 */
Window_Command.prototype.currentExt = function() {
    return this.currentData() ? this.currentData().ext : null;
};

/* 寻找标识 */
Window_Command.prototype.findSymbol = function(symbol) {
    for (var i = 0; i &lt; this._list.length; i) {
        if (this._list[i].symbol === symbol) {
            return i;
        }
    }
    return -1;
};

/* 选择标识 */
Window_Command.prototype.selectSymbol = function(symbol) {
    var index = this.findSymbol(symbol);
    if (index &gt;= 0) {
        this.select(index);
    } else {
        this.select(0);
    }
};

/* 寻找扩展 */
Window_Command.prototype.findExt = function(ext) {
    for (var i = 0; i &lt; this._list.length; i) {
        if (this._list[i].ext === ext) {
            return i;
        }
    }
    return -1;
};

/* 选择扩展 */
Window_Command.prototype.selectExt = function(ext) {
    var index = this.findExt(ext);
    if (index &gt;= 0) {
        this.select(index);
    } else {
        this.select(0);
    }
};

/* 绘制项目 */
Window_Command.prototype.drawItem = function(index) {
    var rect = this.itemRectForText(index);
    var align = this.itemTextAlign();
    this.resetTextColor();
    this.changePaintOpacity(this.isCommandEnabled(index));
    this.drawText(this.commandName(index), rect.x, rect.y, rect.width, align);
};

/* 项目文本对齐 */
Window_Command.prototype.itemTextAlign = function() {
    return 'left';
};

/* 是否确定启用 */
Window_Command.prototype.isOkEnabled = function() {
    return true;
};

/* 呼叫确定处理者 */
Window_Command.prototype.callOkHandler = function() {
    var symbol = this.currentSymbol();
    if (this.isHandled(symbol)) {
        this.callHandler(symbol);
    } else if (this.isHandled('ok')) {
        Window_Selectable.prototype.callOkHandler.call(this);
    } else {
        this.activate();
    }
};

/* 刷新 */
Window_Command.prototype.refresh = function() {
    this.clearCommandList();
    this.makeCommandList();
    this.createContents();
    Window_Selectable.prototype.refresh.call(this);
};

//-----------------------------------------------------------------------------
// 窗口_水平指令 
// Window_HorzCommand
//
// 水平选择格式的指令窗口。 
// The command window for the horizontal selection format.

function Window_HorzCommand() {
    this.initialize.apply(this, arguments);
}

Window_HorzCommand.prototype = Object.create(Window_Command.prototype);
Window_HorzCommand.prototype.constructor = Window_HorzCommand;

/* 初始化 */
Window_HorzCommand.prototype.initialize = function(x, y) {
    Window_Command.prototype.initialize.call(this, x, y);
};

/* 可见的行数 */
Window_HorzCommand.prototype.numVisibleRows = function() {
    return 1;
};

/* 最大列数 */
Window_HorzCommand.prototype.maxCols = function() {
    return 4;
};

/* 项目文本对齐 */
Window_HorzCommand.prototype.itemTextAlign = function() {
    return 'center';
};

//-----------------------------------------------------------------------------
// 窗口_帮助 
// Window_Help
//
// 显示所选项目说明的窗口。 
// The window for displaying the description of the selected item.

function Window_Help() {
    this.initialize.apply(this, arguments);
}

Window_Help.prototype = Object.create(Window_Base.prototype);
Window_Help.prototype.constructor = Window_Help;

/* 初始化 */
Window_Help.prototype.initialize = function(numLines) {
    var width = Graphics.boxWidth;
    var height = this.fittingHeight(numLines || 2);
    Window_Base.prototype.initialize.call(this, 0, 0, width, height);
    this._text = '';
};

/* 设置文本 */
Window_Help.prototype.setText = function(text) {
    if (this._text !== text) {
        this._text = text;
        this.refresh();
    }
};

/* 清除 */
Window_Help.prototype.clear = function() {
    this.setText('');
};

/* 设置项目 */
Window_Help.prototype.setItem = function(item) {
    this.setText(item ? item.description : '');
};

/* 刷新 */
Window_Help.prototype.refresh = function() {
    this.contents.clear();
    this.drawTextEx(this._text, this.textPadding(), 0);
};

//-----------------------------------------------------------------------------
// 窗口_金钱 
// Window_Gold
//
// 显示队伍的金钱的窗口。 
// The window for displaying the party's gold.

function Window_Gold() {
    this.initialize.apply(this, arguments);
}

Window_Gold.prototype = Object.create(Window_Base.prototype);
Window_Gold.prototype.constructor = Window_Gold;

/* 初始化 */
Window_Gold.prototype.initialize = function(x, y) {
    var width = this.windowWidth();
    var height = this.windowHeight();
    Window_Base.prototype.initialize.call(this, x, y, width, height);
    this.refresh();
};

/* 窗口宽度 */
Window_Gold.prototype.windowWidth = function() {
    return 240;
};

/* 窗口高度 */
Window_Gold.prototype.windowHeight = function() {
    return this.fittingHeight(1);
};

/* 刷新 */
Window_Gold.prototype.refresh = function() {
    var x = this.textPadding();
    var width = this.contents.width - this.textPadding() * 2;
    this.contents.clear();
    this.drawCurrencyValue(this.value(), this.currencyUnit(), x, 0, width);
};

/* 值 */
Window_Gold.prototype.value = function() {
    return $gameParty.gold();
};

/* 货币单位 */
Window_Gold.prototype.currencyUnit = function() {
    return TextManager.currencyUnit;
};

/* 打开 */
Window_Gold.prototype.open = function() {
    this.refresh();
    Window_Base.prototype.open.call(this);
};

//-----------------------------------------------------------------------------
// 窗口_菜单指令 
// Window_MenuCommand
//
// 在菜单画面上的选择指令的窗口。 
// The window for selecting a command on the menu screen.

function Window_MenuCommand() {
    this.initialize.apply(this, arguments);
}

Window_MenuCommand.prototype = Object.create(Window_Command.prototype);
Window_MenuCommand.prototype.constructor = Window_MenuCommand;

/* 初始化 */
Window_MenuCommand.prototype.initialize = function(x, y) {
    Window_Command.prototype.initialize.call(this, x, y);
    this.selectLast();
};

Window_MenuCommand._lastCommandSymbol = null;  // 上次选择的指令标识 

/* 初始化指令位置 */
Window_MenuCommand.initCommandPosition = function() {
    this._lastCommandSymbol = null;
};

/* 窗口宽度 */
Window_MenuCommand.prototype.windowWidth = function() {
    return 240;
};

/* 可见的行数 */
Window_MenuCommand.prototype.numVisibleRows = function() {
    return this.maxItems();
};

/* 制作指令列表 */
Window_MenuCommand.prototype.makeCommandList = function() {
    this.addMainCommands();
    this.addFormationCommand();
    this.addOriginalCommands();
    this.addOptionsCommand();
    this.addSaveCommand();
    this.addGameEndCommand();
};

/* 增加主指令 */
Window_MenuCommand.prototype.addMainCommands = function() {
    var enabled = this.areMainCommandsEnabled();
    if (this.needsCommand('item')) {
        this.addCommand(TextManager.item, 'item', enabled);
    }
    if (this.needsCommand('skill')) {
        this.addCommand(TextManager.skill, 'skill', enabled);
    }
    if (this.needsCommand('equip')) {
        this.addCommand(TextManager.equip, 'equip', enabled);
    }
    if (this.needsCommand('status')) {
        this.addCommand(TextManager.status, 'status', enabled);
    }
};

/* 增加整队指令 */
Window_MenuCommand.prototype.addFormationCommand = function() {
    if (this.needsCommand('formation')) {
        var enabled = this.isFormationEnabled();
        this.addCommand(TextManager.formation, 'formation', enabled);
    }
};

/* 增加初始指令 */
Window_MenuCommand.prototype.addOriginalCommands = function() {
};

/* 增加设置指令 */
Window_MenuCommand.prototype.addOptionsCommand = function() {
    if (this.needsCommand('options')) {
        var enabled = this.isOptionsEnabled();
        this.addCommand(TextManager.options, 'options', enabled);
    }
};

/* 增加保存指令 */
Window_MenuCommand.prototype.addSaveCommand = function() {
    if (this.needsCommand('save')) {
        var enabled = this.isSaveEnabled();
        this.addCommand(TextManager.save, 'save', enabled);
    }
};

/* 增加游戏结束指令 */
Window_MenuCommand.prototype.addGameEndCommand = function() {
    var enabled = this.isGameEndEnabled();
    this.addCommand(TextManager.gameEnd, 'gameEnd', enabled);
};

/* 是否需要该指令 */
Window_MenuCommand.prototype.needsCommand = function(name) {
    var flags = $dataSystem.menuCommands;
    if (flags) {
        switch (name) {
        case 'item':
            return flags[0];
        case 'skill':
            return flags[1];
        case 'equip':
            return flags[2];
        case 'status':
            return flags[3];
        case 'formation':
            return flags[4];
        case 'save':
            return flags[5];
        }
    }
    return true;
};

/* 是否主指令启用 */
Window_MenuCommand.prototype.areMainCommandsEnabled = function() {
    return $gameParty.exists();
};

/* 是否整队启用 */
Window_MenuCommand.prototype.isFormationEnabled = function() {
    return $gameParty.size() &gt;= 2 &amp;&amp; $gameSystem.isFormationEnabled();
};

/* 是否设置启用 */
Window_MenuCommand.prototype.isOptionsEnabled = function() {
    return true;
};

/* 是否保存启用 */
Window_MenuCommand.prototype.isSaveEnabled = function() {
    return !DataManager.isEventTest() &amp;&amp; $gameSystem.isSaveEnabled();
};

/* 是否游戏结束启用 */
Window_MenuCommand.prototype.isGameEndEnabled = function() {
    return true;
};

/* 处理确定 */
Window_MenuCommand.prototype.processOk = function() {
    Window_MenuCommand._lastCommandSymbol = this.currentSymbol();
    Window_Command.prototype.processOk.call(this);
};

/* 选择上一个 */
Window_MenuCommand.prototype.selectLast = function() {
    this.selectSymbol(Window_MenuCommand._lastCommandSymbol);
};

//-----------------------------------------------------------------------------
// 窗口_菜单状态 
// Window_MenuStatus
//
// 在菜单画面上显示的队伍状态的窗口。 
// The window for displaying party member status on the menu screen.

function Window_MenuStatus() {
    this.initialize.apply(this, arguments);
}

Window_MenuStatus.prototype = Object.create(Window_Selectable.prototype);
Window_MenuStatus.prototype.constructor = Window_MenuStatus;

/* 初始化 */
Window_MenuStatus.prototype.initialize = function(x, y) {
    var width = this.windowWidth();
    var height = this.windowHeight();
    Window_Selectable.prototype.initialize.call(this, x, y, width, height);
    this._formationMode = false;
    this._pendingIndex = -1;
    this.refresh();
};

/* 窗口宽度 */
Window_MenuStatus.prototype.windowWidth = function() {
    return Graphics.boxWidth - 240;
};

/* 窗口高度 */
Window_MenuStatus.prototype.windowHeight = function() {
    return Graphics.boxHeight;
};

/* 最大项目数 */
Window_MenuStatus.prototype.maxItems = function() {
    return $gameParty.size();
};

/* 项目高度 */
Window_MenuStatus.prototype.itemHeight = function() {
    var clientHeight = this.height - this.padding * 2;
    return Math.floor(clientHeight / this.numVisibleRows());
};

/* 可见的行数 */
Window_MenuStatus.prototype.numVisibleRows = function() {
    return 4;
};

/* 加载图像 */
Window_MenuStatus.prototype.loadImages = function() {
    $gameParty.members().forEach(function(actor) {
        ImageManager.reserveFace(actor.faceName());
    }, this);
};

/* 绘制项目 */
Window_MenuStatus.prototype.drawItem = function(index) {
    this.drawItemBackground(index);
    this.drawItemImage(index);
    this.drawItemStatus(index);
};

/* 绘制项目背景 */
Window_MenuStatus.prototype.drawItemBackground = function(index) {
    if (index === this._pendingIndex) {
        var rect = this.itemRect(index);
        var color = this.pendingColor();
        this.changePaintOpacity(false);
        this.contents.fillRect(rect.x, rect.y, rect.width, rect.height, color);
        this.changePaintOpacity(true);
    }
};

/* 绘制项目图像 */
Window_MenuStatus.prototype.drawItemImage = function(index) {
    var actor = $gameParty.members()[index];
    var rect = this.itemRect(index);
    this.changePaintOpacity(actor.isBattleMember());
    this.drawActorFace(actor, rect.x + 1, rect.y + 1, Window_Base._faceWidth, Window_Base._faceHeight);
    this.changePaintOpacity(true);
};

/* 绘制项目状态 */
Window_MenuStatus.prototype.drawItemStatus = function(index) {
    var actor = $gameParty.members()[index];
    var rect = this.itemRect(index);
    var x = rect.x + 162;
    var y = rect.y + rect.height / 2 - this.lineHeight() * 1.5;
    var width = rect.width - x - this.textPadding();
    this.drawActorSimpleStatus(actor, x, y, width);
};

/* 处理确定 */
Window_MenuStatus.prototype.processOk = function() {
    Window_Selectable.prototype.processOk.call(this);
    $gameParty.setMenuActor($gameParty.members()[this.index()]);
};

/* 是否当前项目启用 */
Window_MenuStatus.prototype.isCurrentItemEnabled = function() {
    if (this._formationMode) {
        var actor = $gameParty.members()[this.index()];
        return actor &amp;&amp; actor.isFormationChangeOk();
    } else {
        return true;
    }
};

/* 选择上一个 */
Window_MenuStatus.prototype.selectLast = function() {
    this.select($gameParty.menuActor().index() || 0);
};

/* 整队模式 */
Window_MenuStatus.prototype.formationMode = function() {
    return this._formationMode;
};

/* 设置整队模式 */
Window_MenuStatus.prototype.setFormationMode = function(formationMode) {
    this._formationMode = formationMode;
};

/* 待定索引 
 * pending 指那个背景光标闪烁的选项。
 */
Window_MenuStatus.prototype.pendingIndex = function() {
    return this._pendingIndex;
};

/* 设置待定索引 */
Window_MenuStatus.prototype.setPendingIndex = function(index) {
    var lastPendingIndex = this._pendingIndex;
    this._pendingIndex = index;
    this.redrawItem(this._pendingIndex);
    this.redrawItem(lastPendingIndex);
};

//-----------------------------------------------------------------------------
// 窗口_菜单角色 
// Window_MenuActor
//
// 在物品和技能画面上的选择目标角色的窗口。 
// The window for selecting a target actor on the item and skill screens.

function Window_MenuActor() {
    this.initialize.apply(this, arguments);
}

Window_MenuActor.prototype = Object.create(Window_MenuStatus.prototype);
Window_MenuActor.prototype.constructor = Window_MenuActor;

/* 初始化 */
Window_MenuActor.prototype.initialize = function() {
    Window_MenuStatus.prototype.initialize.call(this, 0, 0);
    this.hide();
};

/* 处理确定 */
Window_MenuActor.prototype.processOk = function() {
    if (!this.cursorAll()) {
        $gameParty.setTargetActor($gameParty.members()[this.index()]);
    }
    this.callOkHandler();
};

/* 选择上一个 */
Window_MenuActor.prototype.selectLast = function() {
    this.select($gameParty.targetActor().index() || 0);
};

/* 选择该项目 */
Window_MenuActor.prototype.selectForItem = function(item) {
    var actor = $gameParty.menuActor();
    var action = new Game_Action(actor);
    action.setItemObject(item);
    this.setCursorFixed(false);
    this.setCursorAll(false);
    if (action.isForUser()) {
        if (DataManager.isSkill(item)) {
            this.setCursorFixed(true);
            this.select(actor.index());
        } else {
            this.selectLast();
        }
    } else if (action.isForAll()) {
        this.setCursorAll(true);
        this.select(0);
    } else {
        this.selectLast();
    }
};

//-----------------------------------------------------------------------------
// 窗口_物品类型 
// Window_ItemCategory
//
// 在物品和商店画面上的选择物品类型的窗口。 
// The window for selecting a category of items on the item and shop screens.

function Window_ItemCategory() {
    this.initialize.apply(this, arguments);
}

Window_ItemCategory.prototype = Object.create(Window_HorzCommand.prototype);
Window_ItemCategory.prototype.constructor = Window_ItemCategory;

/* 初始化 */
Window_ItemCategory.prototype.initialize = function() {
    Window_HorzCommand.prototype.initialize.call(this, 0, 0);
};

/* 窗口宽度 */
Window_ItemCategory.prototype.windowWidth = function() {
    return Graphics.boxWidth;
};

/* 最大列数 */
Window_ItemCategory.prototype.maxCols = function() {
    return 4;
};

/* 更新 */
Window_ItemCategory.prototype.update = function() {
    Window_HorzCommand.prototype.update.call(this);
    if (this._itemWindow) {
        this._itemWindow.setCategory(this.currentSymbol());
    }
};

/* 制作指令列表 */
Window_ItemCategory.prototype.makeCommandList = function() {
    this.addCommand(TextManager.item,    'item');
    this.addCommand(TextManager.weapon,  'weapon');
    this.addCommand(TextManager.armor,   'armor');
    this.addCommand(TextManager.keyItem, 'keyItem');
};

/* 设置物品窗口 */
Window_ItemCategory.prototype.setItemWindow = function(itemWindow) {
    this._itemWindow = itemWindow;
};

//-----------------------------------------------------------------------------
// 窗口_物品列表 
// Window_ItemList
//
// 在物品画面上的选择物品的窗口。 
// The window for selecting an item on the item screen.

function Window_ItemList() {
    this.initialize.apply(this, arguments);
}

Window_ItemList.prototype = Object.create(Window_Selectable.prototype);
Window_ItemList.prototype.constructor = Window_ItemList;

/* 初始化 */
Window_ItemList.prototype.initialize = function(x, y, width, height) {
    Window_Selectable.prototype.initialize.call(this, x, y, width, height);
    this._category = 'none';
    this._data = [];
};

/* 设置类别 */
Window_ItemList.prototype.setCategory = function(category) {
    if (this._category !== category) {
        this._category = category;
        this.refresh();
        this.resetScroll();
    }
};

/* 最大列数 */
Window_ItemList.prototype.maxCols = function() {
    return 2;
};

/* 间距 */
Window_ItemList.prototype.spacing = function() {
    return 48;
};

/* 最大项目数 */
Window_ItemList.prototype.maxItems = function() {
    return this._data ? this._data.length : 1;
};

/* 项目 */
Window_ItemList.prototype.item = function() {
    var index = this.index();
    return this._data &amp;&amp; index &gt;= 0 ? this._data[index] : null;
};

/* 是否当前项目启用 */
Window_ItemList.prototype.isCurrentItemEnabled = function() {
    return this.isEnabled(this.item());
};

/* 包含 */
Window_ItemList.prototype.includes = function(item) {
    switch (this._category) {
    case 'item':
        return DataManager.isItem(item) &amp;&amp; item.itypeId === 1;
    case 'weapon':
        return DataManager.isWeapon(item);
    case 'armor':
        return DataManager.isArmor(item);
    case 'keyItem':
        return DataManager.isItem(item) &amp;&amp; item.itypeId === 2;
    default:
        return false;
    }
};

/* 是否需要数量 */
Window_ItemList.prototype.needsNumber = function() {
    return true;
};

/* 是否启用 */
Window_ItemList.prototype.isEnabled = function(item) {
    return $gameParty.canUse(item);
};

/* 制作项目列表 */
Window_ItemList.prototype.makeItemList = function() {
    this._data = $gameParty.allItems().filter(function(item) {
        return this.includes(item);
    }, this);
    if (this.includes(null)) {
        this._data.push(null);
    }
};

/* 选择上一个 */
Window_ItemList.prototype.selectLast = function() {
    var index = this._data.indexOf($gameParty.lastItem());
    this.select(index &gt;= 0 ? index : 0);
};

/* 绘制项目 */
Window_ItemList.prototype.drawItem = function(index) {
    var item = this._data[index];
    if (item) {
        var numberWidth = this.numberWidth();
        var rect = this.itemRect(index);
        rect.width -= this.textPadding();
        this.changePaintOpacity(this.isEnabled(item));
        this.drawItemName(item, rect.x, rect.y, rect.width - numberWidth);
        this.drawItemNumber(item, rect.x, rect.y, rect.width);
        this.changePaintOpacity(1);
    }
};

/* 数字宽度 */
Window_ItemList.prototype.numberWidth = function() {
    return this.textWidth('000');
};

/* 绘制物品数量 */
Window_ItemList.prototype.drawItemNumber = function(item, x, y, width) {
    if (this.needsNumber()) {
        this.drawText(':', x, y, width - this.textWidth('00'), 'right');
        this.drawText($gameParty.numItems(item), x, y, width, 'right');
    }
};

/* 更新帮助 */
Window_ItemList.prototype.updateHelp = function() {
    this.setHelpWindowItem(this.item());
};

/* 刷新 */
Window_ItemList.prototype.refresh = function() {
    this.makeItemList();
    this.createContents();
    this.drawAllItems();
};

//----------------------------------------------------------------------------
// 窗口技能类型 
// Window_SkillType
//
// 在技能画面上的选择技能类型的窗口。 
// The window for selecting a skill type on the skill screen.

function Window_SkillType() {
    this.initialize.apply(this, arguments);
}

Window_SkillType.prototype = Object.create(Window_Command.prototype);
Window_SkillType.prototype.constructor = Window_SkillType;

/* 初始化 */
Window_SkillType.prototype.initialize = function(x, y) {
    Window_Command.prototype.initialize.call(this, x, y);
    this._actor = null;
};

/* 窗口宽度 */
Window_SkillType.prototype.windowWidth = function() {
    return 240;
};

/* 设置角色 */
Window_SkillType.prototype.setActor = function(actor) {
    if (this._actor !== actor) {
        this._actor = actor;
        this.refresh();
        this.selectLast();
    }
};

/* 可见的行数 */
Window_SkillType.prototype.numVisibleRows = function() {
    return 4;
};

/* 制作指令列表 */
Window_SkillType.prototype.makeCommandList = function() {
    if (this._actor) {
        var skillTypes = this._actor.addedSkillTypes();
        skillTypes.sort(function(a, b) {
            return a - b;
        });
        skillTypes.forEach(function(stypeId) {
            var name = $dataSystem.skillTypes[stypeId];
            this.addCommand(name, 'skill', true, stypeId);
        }, this);
    }
};

/* 更新 */
Window_SkillType.prototype.update = function() {
    Window_Command.prototype.update.call(this);
    if (this._skillWindow) {
        this._skillWindow.setStypeId(this.currentExt());
    }
};

/* 设置技能窗口 */
Window_SkillType.prototype.setSkillWindow = function(skillWindow) {
    this._skillWindow = skillWindow;
};

/* 选择上一个 */
Window_SkillType.prototype.selectLast = function() {
    var skill = this._actor.lastMenuSkill();
    if (skill) {
        this.selectExt(skill.stypeId);
    } else {
        this.select(0);
    }
};

//-----------------------------------------------------------------------------
// 窗口_技能状态 
// Window_SkillStatus
//
// 在技能画面上的显示技能使用者状态的窗口。 
// The window for displaying the skill user's status on the skill screen.

function Window_SkillStatus() {
    this.initialize.apply(this, arguments);
}

Window_SkillStatus.prototype = Object.create(Window_Base.prototype);
Window_SkillStatus.prototype.constructor = Window_SkillStatus;

/* 初始化 */
Window_SkillStatus.prototype.initialize = function(x, y, width, height) {
    Window_Base.prototype.initialize.call(this, x, y, width, height);
    this._actor = null;
};

/* 设置角色 */
Window_SkillStatus.prototype.setActor = function(actor) {
    if (this._actor !== actor) {
        this._actor = actor;
        this.refresh();
    }
};

/* 刷新 */
Window_SkillStatus.prototype.refresh = function() {
    this.contents.clear();
    if (this._actor) {
        var w = this.width - this.padding * 2;
        var h = this.height - this.padding * 2;
        var y = h / 2 - this.lineHeight() * 1.5;
        var width = w - 162 - this.textPadding();
        this.drawActorFace(this._actor, 0, 0, 144, h);
        this.drawActorSimpleStatus(this._actor, 162, y, width);
    }
};

//-----------------------------------------------------------------------------
// 窗口_技能列表 
// Window_SkillList
//
// 在技能画面上的选择技能的窗口。 
// The window for selecting a skill on the skill screen.

function Window_SkillList() {
    this.initialize.apply(this, arguments);
}

Window_SkillList.prototype = Object.create(Window_Selectable.prototype);
Window_SkillList.prototype.constructor = Window_SkillList;

/* 初始化 */
Window_SkillList.prototype.initialize = function(x, y, width, height) {
    Window_Selectable.prototype.initialize.call(this, x, y, width, height);
    this._actor = null;
    this._stypeId = 0;
    this._data = [];
};

/* 设置角色 */
Window_SkillList.prototype.setActor = function(actor) {
    if (this._actor !== actor) {
        this._actor = actor;
        this.refresh();
        this.resetScroll();
    }
};

/* 设置技能类型 ID */
Window_SkillList.prototype.setStypeId = function(stypeId) {
    if (this._stypeId !== stypeId) {
        this._stypeId = stypeId;
        this.refresh();
        this.resetScroll();
    }
};

/* 最大列数 */
Window_SkillList.prototype.maxCols = function() {
    return 2;
};

/* 间距 */
Window_SkillList.prototype.spacing = function() {
    return 48;
};

/* 最大项目数 */
Window_SkillList.prototype.maxItems = function() {
    return this._data ? this._data.length : 1;
};

/* 项目 */
Window_SkillList.prototype.item = function() {
    return this._data &amp;&amp; this.index() &gt;= 0 ? this._data[this.index()] : null;
};

/* 是否当前项目启用 */
Window_SkillList.prototype.isCurrentItemEnabled = function() {
    return this.isEnabled(this._data[this.index()]);
};

/* 包含 */
Window_SkillList.prototype.includes = function(item) {
    return item &amp;&amp; item.stypeId === this._stypeId;
};

/* 是否启用 */
Window_SkillList.prototype.isEnabled = function(item) {
    return this._actor &amp;&amp; this._actor.canUse(item);
};

/* 制作项目列表 */
Window_SkillList.prototype.makeItemList = function() {
    if (this._actor) {
        this._data = this._actor.skills().filter(function(item) {
            return this.includes(item);
        }, this);
    } else {
        this._data = [];
    }
};

/* 选择上一个 */
Window_SkillList.prototype.selectLast = function() {
    var skill;
    if ($gameParty.inBattle()) {
        skill = this._actor.lastBattleSkill();
    } else {
        skill = this._actor.lastMenuSkill();
    }
    var index = this._data.indexOf(skill);
    this.select(index &gt;= 0 ? index : 0);
};

/* 绘制项目 */
Window_SkillList.prototype.drawItem = function(index) {
    var skill = this._data[index];
    if (skill) {
        var costWidth = this.costWidth();
        var rect = this.itemRect(index);
        rect.width -= this.textPadding();
        this.changePaintOpacity(this.isEnabled(skill));
        this.drawItemName(skill, rect.x, rect.y, rect.width - costWidth);
        this.drawSkillCost(skill, rect.x, rect.y, rect.width);
        this.changePaintOpacity(1);
    }
};

/* 消耗的宽度 */
Window_SkillList.prototype.costWidth = function() {
    return this.textWidth('000');
};

/* 绘制技能消耗 */
Window_SkillList.prototype.drawSkillCost = function(skill, x, y, width) {
    if (this._actor.skillTpCost(skill) &gt; 0) {
        this.changeTextColor(this.tpCostColor());
        this.drawText(this._actor.skillTpCost(skill), x, y, width, 'right');
    } else if (this._actor.skillMpCost(skill) &gt; 0) {
        this.changeTextColor(this.mpCostColor());
        this.drawText(this._actor.skillMpCost(skill), x, y, width, 'right');
    }
};

/* 更新帮助 */
Window_SkillList.prototype.updateHelp = function() {
    this.setHelpWindowItem(this.item());
};

/* 刷新 */
Window_SkillList.prototype.refresh = function() {
    this.makeItemList();
    this.createContents();
    this.drawAllItems();
};

//-----------------------------------------------------------------------------
// 窗口_装备状态 
// Window_EquipStatus
//
// 在装备画面上的显示能力值变化的窗口。 
// The window for displaying parameter changes on the equipment screen.

function Window_EquipStatus() {
    this.initialize.apply(this, arguments);
}

Window_EquipStatus.prototype = Object.create(Window_Base.prototype);
Window_EquipStatus.prototype.constructor = Window_EquipStatus;

/* 初始化 */
Window_EquipStatus.prototype.initialize = function(x, y) {
    var width = this.windowWidth();
    var height = this.windowHeight();
    Window_Base.prototype.initialize.call(this, x, y, width, height);
    this._actor = null;
    this._tempActor = null;
    this.refresh();
};

/* 窗口宽度 */
Window_EquipStatus.prototype.windowWidth = function() {
    return 312;
};

/* 窗口高度 */
Window_EquipStatus.prototype.windowHeight = function() {
    return this.fittingHeight(this.numVisibleRows());
};

/* 可见的行数 */
Window_EquipStatus.prototype.numVisibleRows = function() {
    return 7;
};

/* 设置角色 */
Window_EquipStatus.prototype.setActor = function(actor) {
    if (this._actor !== actor) {
        this._actor = actor;
        this.refresh();
    }
};

/* 刷新 */
Window_EquipStatus.prototype.refresh = function() {
    this.contents.clear();
    if (this._actor) {
        this.drawActorName(this._actor, this.textPadding(), 0);
        for (var i = 0; i &lt; 6; i) {
            this.drawItem(0, this.lineHeight() * (1 + i), 2 + i);
        }
    }
};

/* 设置临时角色 
 * 给临时角色对象设置新装备用于比较能力值变化。 
 */
Window_EquipStatus.prototype.setTempActor = function(tempActor) {
    if (this._tempActor !== tempActor) {
        this._tempActor = tempActor;
        this.refresh();
    }
};

/* 绘制项目 */
Window_EquipStatus.prototype.drawItem = function(x, y, paramId) {
    this.drawParamName(x + this.textPadding(), y, paramId);
    if (this._actor) {
        this.drawCurrentParam(x + 140, y, paramId);
    }
    this.drawRightArrow(x + 188, y);
    if (this._tempActor) {
        this.drawNewParam(x + 222, y, paramId);
    }
};

/* 绘制能力值名字 */
Window_EquipStatus.prototype.drawParamName = function(x, y, paramId) {
    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.param(paramId), x, y, 120);
};

/* 绘制当前能力值 */
Window_EquipStatus.prototype.drawCurrentParam = function(x, y, paramId) {
    this.resetTextColor();
    this.drawText(this._actor.param(paramId), x, y, 48, 'right');
};

/* 绘制右箭头 */
Window_EquipStatus.prototype.drawRightArrow = function(x, y) {
    this.changeTextColor(this.systemColor());
    this.drawText('\u2192', x, y, 32, 'center');
};

/* 绘制新能力值 */
Window_EquipStatus.prototype.drawNewParam = function(x, y, paramId) {
    var newValue = this._tempActor.param(paramId);
    var diffvalue = newValue - this._actor.param(paramId);
    this.changeTextColor(this.paramchangeTextColor(diffvalue));
    this.drawText(newValue, x, y, 48, 'right');
};

//-----------------------------------------------------------------------------
// 窗口_装备指令 
// Window_EquipCommand
//
// 在装备画面上的选择指令的窗口。 
// The window for selecting a command on the equipment screen.

function Window_EquipCommand() {
    this.initialize.apply(this, arguments);
}

Window_EquipCommand.prototype = Object.create(Window_HorzCommand.prototype);
Window_EquipCommand.prototype.constructor = Window_EquipCommand;

/* 初始化 */
Window_EquipCommand.prototype.initialize = function(x, y, width) {
    this._windowWidth = width;
    Window_HorzCommand.prototype.initialize.call(this, x, y);
};

/* 窗口宽度 */
Window_EquipCommand.prototype.windowWidth = function() {
    return this._windowWidth;
};

/* 最大列数 */
Window_EquipCommand.prototype.maxCols = function() {
    return 3;
};

/* 制作指令列表 */
Window_EquipCommand.prototype.makeCommandList = function() {
    this.addCommand(TextManager.equip2,   'equip');
    this.addCommand(TextManager.optimize, 'optimize');
    this.addCommand(TextManager.clear,    'clear');
};

//-----------------------------------------------------------------------------
// 窗口_装备槽 
// Window_EquipSlot
// 
// 在装备画面上的选择装备槽的窗口。 
// The window for selecting an equipment slot on the equipment screen.

function Window_EquipSlot() {
    this.initialize.apply(this, arguments);
}

Window_EquipSlot.prototype = Object.create(Window_Selectable.prototype);
Window_EquipSlot.prototype.constructor = Window_EquipSlot;

/* 初始化 */
Window_EquipSlot.prototype.initialize = function(x, y, width, height) {
    Window_Selectable.prototype.initialize.call(this, x, y, width, height);
    this._actor = null;
    this.refresh();
};

/* 设置角色 */
Window_EquipSlot.prototype.setActor = function(actor) {
    if (this._actor !== actor) {
        this._actor = actor;
        this.refresh();
    }
};

/* 更新 */
Window_EquipSlot.prototype.update = function() {
    Window_Selectable.prototype.update.call(this);
    if (this._itemWindow) {
        this._itemWindow.setSlotId(this.index());
    }
};

/* 最大项目数 */
Window_EquipSlot.prototype.maxItems = function() {
    return this._actor ? this._actor.equipSlots().length : 0;
};

/* 项目 */
Window_EquipSlot.prototype.item = function() {
    return this._actor ? this._actor.equips()[this.index()] : null;
};

/* 绘制项目 */
Window_EquipSlot.prototype.drawItem = function(index) {
    if (this._actor) {
        var rect = this.itemRectForText(index);
        this.changeTextColor(this.systemColor());
        this.changePaintOpacity(this.isEnabled(index));
        this.drawText(this.slotName(index), rect.x, rect.y, 138, this.lineHeight());
        this.drawItemName(this._actor.equips()[index], rect.x + 138, rect.y);
        this.changePaintOpacity(true);
    }
};

/* 槽名 */
Window_EquipSlot.prototype.slotName = function(index) {
    var slots = this._actor.equipSlots();
    return this._actor ? $dataSystem.equipTypes[slots[index]] : '';
};

/* 是否启用 */
Window_EquipSlot.prototype.isEnabled = function(index) {
    return this._actor ? this._actor.isEquipChangeOk(index) : false;
};

/* 是否当前项目启用 */
Window_EquipSlot.prototype.isCurrentItemEnabled = function() {
    return this.isEnabled(this.index());
};

/* 设置状态窗口 */
Window_EquipSlot.prototype.setStatusWindow = function(statusWindow) {
    this._statusWindow = statusWindow;
    this.callUpdateHelp();
};

/* 设置项目窗口 */
Window_EquipSlot.prototype.setItemWindow = function(itemWindow) {
    this._itemWindow = itemWindow;
};

/* 更新帮助 */
Window_EquipSlot.prototype.updateHelp = function() {
    Window_Selectable.prototype.updateHelp.call(this);
    this.setHelpWindowItem(this.item());
    if (this._statusWindow) {
        this._statusWindow.setTempActor(null);
    }
};

//-----------------------------------------------------------------------------
// 窗口_装备物品 
// Window_EquipItem
//
// 在装备画面上选择的装备物品的窗口。 
// The window for selecting an equipment item on the equipment screen.

function Window_EquipItem() {
    this.initialize.apply(this, arguments);
}

Window_EquipItem.prototype = Object.create(Window_ItemList.prototype);
Window_EquipItem.prototype.constructor = Window_EquipItem;

/* 初始化 */
Window_EquipItem.prototype.initialize = function(x, y, width, height) {
    Window_ItemList.prototype.initialize.call(this, x, y, width, height);
    this._actor = null;
    this._slotId = 0;
};

/* 设置角色 */
Window_EquipItem.prototype.setActor = function(actor) {
    if (this._actor !== actor) {
        this._actor = actor;
        this.refresh();
        this.resetScroll();
    }
};

/* 设置槽 ID */
Window_EquipItem.prototype.setSlotId = function(slotId) {
    if (this._slotId !== slotId) {
        this._slotId = slotId;
        this.refresh();
        this.resetScroll();
    }
};

/* 包含 */
Window_EquipItem.prototype.includes = function(item) {
    if (item === null) {
        return true;
    }
    if (this._slotId &lt; 0 || item.etypeId !== this._actor.equipSlots()[this._slotId]) {
        return false;
    }
    return this._actor.canEquip(item);
};

/* 是否启用 */
Window_EquipItem.prototype.isEnabled = function(item) {
    return true;
};

/* 选择上一个 */
Window_EquipItem.prototype.selectLast = function() {
};

/* 设置状态窗口 */
Window_EquipItem.prototype.setStatusWindow = function(statusWindow) {
    this._statusWindow = statusWindow;
    this.callUpdateHelp();
};

/* 更新帮助 */
Window_EquipItem.prototype.updateHelp = function() {
    Window_ItemList.prototype.updateHelp.call(this);
    if (this._actor &amp;&amp; this._statusWindow) {
        var actor = JsonEx.makeDeepCopy(this._actor);
        actor.forceChangeEquip(this._slotId, this.item());
        this._statusWindow.setTempActor(actor);
    }
};

/* 播放确定声音 */
Window_EquipItem.prototype.playOkSound = function() {
};

//-----------------------------------------------------------------------------
// 窗口_状态 
// Window_Status
//
// 在状态画面上的显示完整状态的窗口。 
// The window for displaying full status on the status screen.

function Window_Status() {
    this.initialize.apply(this, arguments);
}

Window_Status.prototype = Object.create(Window_Selectable.prototype);
Window_Status.prototype.constructor = Window_Status;

/* 初始化 */
Window_Status.prototype.initialize = function() {
    var width = Graphics.boxWidth;
    var height = Graphics.boxHeight;
    Window_Selectable.prototype.initialize.call(this, 0, 0, width, height);
    this._actor = null;
    this.refresh();
    this.activate();
};

/* 设置角色 */
Window_Status.prototype.setActor = function(actor) {
    if (this._actor !== actor) {
        this._actor = actor;
        this.refresh();
    }
};

/* 刷新 */
Window_Status.prototype.refresh = function() {
    this.contents.clear();
    if (this._actor) {
        var lineHeight = this.lineHeight();
        this.drawBlock1(lineHeight * 0);
        this.drawHorzLine(lineHeight * 1);
        this.drawBlock2(lineHeight * 2);
        this.drawHorzLine(lineHeight * 6);
        this.drawBlock3(lineHeight * 7);
        this.drawHorzLine(lineHeight * 13);
        this.drawBlock4(lineHeight * 14);
    }
};

/* 绘制块 1 */
Window_Status.prototype.drawBlock1 = function(y) {
    this.drawActorName(this._actor, 6, y);
    this.drawActorClass(this._actor, 192, y);
    this.drawActorNickname(this._actor, 432, y);
};

/* 绘制块 2 */
Window_Status.prototype.drawBlock2 = function(y) {
    this.drawActorFace(this._actor, 12, y);
    this.drawBasicInfo(204, y);
    this.drawExpInfo(456, y);
};

/* 绘制块 3 */
Window_Status.prototype.drawBlock3 = function(y) {
    this.drawParameters(48, y);
    this.drawEquipments(432, y);
};

/* 绘制块 4 */
Window_Status.prototype.drawBlock4 = function(y) {
    this.drawProfile(6, y);
};

/* 绘制水平线 */
Window_Status.prototype.drawHorzLine = function(y) {
    var lineY = y + this.lineHeight() / 2 - 1;
    this.contents.paintOpacity = 48;
    this.contents.fillRect(0, lineY, this.contentsWidth(), 2, this.lineColor());
    this.contents.paintOpacity = 255;
};

/* 线颜色 */
Window_Status.prototype.lineColor = function() {
    return this.normalColor();
};

/* 绘制基本信息 */
Window_Status.prototype.drawBasicInfo = function(x, y) {
    var lineHeight = this.lineHeight();
    this.drawActorLevel(this._actor, x, y + lineHeight * 0);
    this.drawActorIcons(this._actor, x, y + lineHeight * 1);
    this.drawActorHp(this._actor, x, y + lineHeight * 2);
    this.drawActorMp(this._actor, x, y + lineHeight * 3);
};

/* 绘制能力值 */
Window_Status.prototype.drawParameters = function(x, y) {
    var lineHeight = this.lineHeight();
    for (var i = 0; i &lt; 6; i) {
        var paramId = i + 2;
        var y2 = y + lineHeight * i;
        this.changeTextColor(this.systemColor());
        this.drawText(TextManager.param(paramId), x, y2, 160);
        this.resetTextColor();
        this.drawText(this._actor.param(paramId), x + 160, y2, 60, 'right');
    }
};

/* 绘制经验信息 */
Window_Status.prototype.drawExpInfo = function(x, y) {
    var lineHeight = this.lineHeight();
    var expTotal = TextManager.expTotal.format(TextManager.exp);
    var expNext = TextManager.expNext.format(TextManager.level);
    var value1 = this._actor.currentExp();
    var value2 = this._actor.nextRequiredExp();
    if (this._actor.isMaxLevel()) {
        value1 = '-------';
        value2 = '-------';
    }
    this.changeTextColor(this.systemColor());
    this.drawText(expTotal, x, y + lineHeight * 0, 270);
    this.drawText(expNext, x, y + lineHeight * 2, 270);
    this.resetTextColor();
    this.drawText(value1, x, y + lineHeight * 1, 270, 'right');
    this.drawText(value2, x, y + lineHeight * 3, 270, 'right');
};

/* 绘制装备 */
Window_Status.prototype.drawEquipments = function(x, y) {
    var equips = this._actor.equips();
    var count = Math.min(equips.length, this.maxEquipmentLines());
    for (var i = 0; i &lt; count; i) {
        this.drawItemName(equips[i], x, y + this.lineHeight() * i);
    }
};

/* 绘制简介 */
Window_Status.prototype.drawProfile = function(x, y) {
    this.drawTextEx(this._actor.profile(), x, y);
};

/* 最大装备行 */
Window_Status.prototype.maxEquipmentLines = function() {
    return 6;
};

//-----------------------------------------------------------------------------
// 窗口_设置 
// Window_Options
//
// 设置画面上的更改各种设置的窗口。 
// The window for changing various settings on the options screen.

function Window_Options() {
    this.initialize.apply(this, arguments);
}

Window_Options.prototype = Object.create(Window_Command.prototype);
Window_Options.prototype.constructor = Window_Options;

/* 初始化 */
Window_Options.prototype.initialize = function() {
    Window_Command.prototype.initialize.call(this, 0, 0);
    this.updatePlacement();
};

/* 窗口宽度 */
Window_Options.prototype.windowWidth = function() {
    return 400;
};

/* 窗口高度 */
Window_Options.prototype.windowHeight = function() {
    return this.fittingHeight(Math.min(this.numVisibleRows(), 12));
};

/* 更新位置 */
Window_Options.prototype.updatePlacement = function() {
    this.x = (Graphics.boxWidth - this.width) / 2;
    this.y = (Graphics.boxHeight - this.height) / 2;
};

/* 制作指令列表 */
Window_Options.prototype.makeCommandList = function() {
    this.addGeneralOptions();
    this.addVolumeOptions();
};

/* 增加一般选项 */
Window_Options.prototype.addGeneralOptions = function() {
    this.addCommand(TextManager.alwaysDash, 'alwaysDash');
    this.addCommand(TextManager.commandRemember, 'commandRemember');
};

/* 增加音量选项 */
Window_Options.prototype.addVolumeOptions = function() {
    this.addCommand(TextManager.bgmVolume, 'bgmVolume');
    this.addCommand(TextManager.bgsVolume, 'bgsVolume');
    this.addCommand(TextManager.meVolume, 'meVolume');
    this.addCommand(TextManager.seVolume, 'seVolume');
};

/* 绘制项目 */
Window_Options.prototype.drawItem = function(index) {
    var rect = this.itemRectForText(index);
    var statusWidth = this.statusWidth();
    var titleWidth = rect.width - statusWidth;
    this.resetTextColor();
    this.changePaintOpacity(this.isCommandEnabled(index));
    this.drawText(this.commandName(index), rect.x, rect.y, titleWidth, 'left');
    this.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'right');
};

/* 状态宽度 */
Window_Options.prototype.statusWidth = function() {
    return 120;
};

/* 状态文本 */
Window_Options.prototype.statusText = function(index) {
    var symbol = this.commandSymbol(index);
    var value = this.getConfigValue(symbol);
    if (this.isVolumeSymbol(symbol)) {
        return this.volumeStatusText(value);
    } else {
        return this.booleanStatusText(value);
    }
};

/* 是否音量标识 */
Window_Options.prototype.isVolumeSymbol = function(symbol) {
    return symbol.contains('Volume');
};

/* 布尔值状态文本 */
Window_Options.prototype.booleanStatusText = function(value) {
    return value ? 'ON' : 'OFF';
};

/* 音量状态文本 */
Window_Options.prototype.volumeStatusText = function(value) {
    return value + '%';
};

/* 处理确定 */
Window_Options.prototype.processOk = function() {
    var index = this.index();
    var symbol = this.commandSymbol(index);
    var value = this.getConfigValue(symbol);
    if (this.isVolumeSymbol(symbol)) {
        value += this.volumeOffset();
        if (value &gt; 100) {
            value = 0;
        }
        value = value.clamp(0, 100);
        this.changeValue(symbol, value);
    } else {
        this.changeValue(symbol, !value);
    }
};

/* 光标向右 */
Window_Options.prototype.cursorRight = function(wrap) {
    var index = this.index();
    var symbol = this.commandSymbol(index);
    var value = this.getConfigValue(symbol);
    if (this.isVolumeSymbol(symbol)) {
        value += this.volumeOffset();
        value = value.clamp(0, 100);
        this.changeValue(symbol, value);
    } else {
        this.changeValue(symbol, true);
    }
};

/* 光标向左 */
Window_Options.prototype.cursorLeft = function(wrap) {
    var index = this.index();
    var symbol = this.commandSymbol(index);
    var value = this.getConfigValue(symbol);
    if (this.isVolumeSymbol(symbol)) {
        value -= this.volumeOffset();
        value = value.clamp(0, 100);
        this.changeValue(symbol, value);
    } else {
        this.changeValue(symbol, false);
    }
};

/* 光标偏移 
 * 一次增减百分几的音量。 
 */
Window_Options.prototype.volumeOffset = function() {
    return 20;
};

/* 改变值 */
Window_Options.prototype.changeValue = function(symbol, value) {
    var lastValue = this.getConfigValue(symbol);
    if (lastValue !== value) {
        this.setConfigValue(symbol, value);
        this.redrawItem(this.findSymbol(symbol));
        SoundManager.playCursor();
    }
};

/* 获取配置值 */
Window_Options.prototype.getConfigValue = function(symbol) {
    return ConfigManager[symbol];
};

/* 设置配置值 */
Window_Options.prototype.setConfigValue = function(symbol, volume) {
    ConfigManager[symbol] = volume;
};

//-----------------------------------------------------------------------------
// 窗口_存档列表 
// Window_SavefileList
//
// 在存档和读档画面上的选择存档的窗口。 
// The window for selecting a save file on the save and load screens.

function Window_SavefileList() {
    this.initialize.apply(this, arguments);
}

Window_SavefileList.prototype = Object.create(Window_Selectable.prototype);
Window_SavefileList.prototype.constructor = Window_SavefileList;

/* 初始化 */
Window_SavefileList.prototype.initialize = function(x, y, width, height) {
    Window_Selectable.prototype.initialize.call(this, x, y, width, height);
    this.activate();
    this._mode = null;
};

/* 设置模式 
 * @param {String} mode 模式（save：保存，load：读取） 
 */
Window_SavefileList.prototype.setMode = function(mode) {
    this._mode = mode;
};

/* 最大项目数 */
Window_SavefileList.prototype.maxItems = function() {
    return DataManager.maxSavefiles();
};

/* 最大可见的项目数 */
Window_SavefileList.prototype.maxVisibleItems = function() {
    return 5;
};

/* 项目高度 */
Window_SavefileList.prototype.itemHeight = function() {
    var innerHeight = this.height - this.padding * 2;
    return Math.floor(innerHeight / this.maxVisibleItems());
};

/* 绘制项目 */
Window_SavefileList.prototype.drawItem = function(index) {
    var id = index + 1;
    var valid = DataManager.isThisGameFile(id);
    var info = DataManager.loadSavefileInfo(id);
    var rect = this.itemRectForText(index);
    this.resetTextColor();
    if (this._mode === 'load') {
        this.changePaintOpacity(valid);
    }
    this.drawFileId(id, rect.x, rect.y);
    if (info) {
        this.changePaintOpacity(valid);
        this.drawContents(info, rect, valid);
        this.changePaintOpacity(true);
    }
};

/* 绘制文件 ID */
Window_SavefileList.prototype.drawFileId = function(id, x, y) {
    this.drawText(TextManager.file + ' ' + id, x, y, 180);
};

/* 绘制内容 */
Window_SavefileList.prototype.drawContents = function(info, rect, valid) {
    var bottom = rect.y + rect.height;
    if (rect.width &gt;= 420) {
        this.drawGameTitle(info, rect.x + 192, rect.y, rect.width - 192);
        if (valid) {
            this.drawPartyCharacters(info, rect.x + 220, bottom - 4);
        }
    }
    var lineHeight = this.lineHeight();
    var y2 = bottom - lineHeight;
    if (y2 &gt;= lineHeight) {
        this.drawPlaytime(info, rect.x, y2, rect.width);
    }
};

/* 绘制游戏标题 */
Window_SavefileList.prototype.drawGameTitle = function(info, x, y, width) {
    if (info.title) {
        this.drawText(info.title, x, y, width);
    }
};

/* 绘制队伍行走图 */
Window_SavefileList.prototype.drawPartyCharacters = function(info, x, y) {
    if (info.characters) {
        for (var i = 0; i &lt; info.characters.length; i) {
            var data = info.characters[i];
            this.drawCharacter(data[0], data[1], x + i * 48, y);
        }
    }
};

/* 绘制游戏时间 */
Window_SavefileList.prototype.drawPlaytime = function(info, x, y, width) {
    if (info.playtime) {
        this.drawText(info.playtime, x, y, width, 'right');
    }
};

/* 播放确定声音 */
Window_SavefileList.prototype.playOkSound = function() {
};

//-----------------------------------------------------------------------------
// 窗口_商店指令 
// Window_ShopCommand
//
// 在商店画面上的选择购买/出售的窗口。 
// The window for selecting buy/sell on the shop screen.

function Window_ShopCommand() {
    this.initialize.apply(this, arguments);
}

Window_ShopCommand.prototype = Object.create(Window_HorzCommand.prototype);
Window_ShopCommand.prototype.constructor = Window_ShopCommand;

/* 初始化 */
Window_ShopCommand.prototype.initialize = function(width, purchaseOnly) {
    this._windowWidth = width;
    this._purchaseOnly = purchaseOnly;
    Window_HorzCommand.prototype.initialize.call(this, 0, 0);
};

/* 窗口宽度 */
Window_ShopCommand.prototype.windowWidth = function() {
    return this._windowWidth;
};

/* 最大列数 */
Window_ShopCommand.prototype.maxCols = function() {
    return 3;
};

/* 制作指令列表 */
Window_ShopCommand.prototype.makeCommandList = function() {
    this.addCommand(TextManager.buy,    'buy');
    this.addCommand(TextManager.sell,   'sell',   !this._purchaseOnly);
    this.addCommand(TextManager.cancel, 'cancel');
};

//-----------------------------------------------------------------------------
// 窗口_商店购买 
// Window_ShopBuy
//
// 在商店画面上的选择要购买的商品的窗口。 
// The window for selecting an item to buy on the shop screen.

function Window_ShopBuy() {
    this.initialize.apply(this, arguments);
}

Window_ShopBuy.prototype = Object.create(Window_Selectable.prototype);
Window_ShopBuy.prototype.constructor = Window_ShopBuy;

/* 初始化 */
Window_ShopBuy.prototype.initialize = function(x, y, height, shopGoods) {
    var width = this.windowWidth();
    Window_Selectable.prototype.initialize.call(this, x, y, width, height);
    this._shopGoods = shopGoods;
    this._money = 0;
    this.refresh();
    this.select(0);
};

/* 窗口宽度 */
Window_ShopBuy.prototype.windowWidth = function() {
    return 456;
};

/* 最大项目数 */
Window_ShopBuy.prototype.maxItems = function() {
    return this._data ? this._data.length : 1;
};

/* 项目 */
Window_ShopBuy.prototype.item = function() {
    return this._data[this.index()];
};

/* 设置金钱 */
Window_ShopBuy.prototype.setMoney = function(money) {
    this._money = money;
    this.refresh();
};

/* 是否当前项目启用 */
Window_ShopBuy.prototype.isCurrentItemEnabled = function() {
    return this.isEnabled(this._data[this.index()]);
};

/* 价格 */
Window_ShopBuy.prototype.price = function(item) {
    return this._price[this._data.indexOf(item)] || 0;
};

/* 是否启用 */
Window_ShopBuy.prototype.isEnabled = function(item) {
    return (item &amp;&amp; this.price(item) &lt;= this._money &amp;&amp;
            !$gameParty.hasMaxItems(item));
};

/* 刷新 */
Window_ShopBuy.prototype.refresh = function() {
    this.makeItemList();
    this.createContents();
    this.drawAllItems();
};

/* 制作项目列表 */
Window_ShopBuy.prototype.makeItemList = function() {
    this._data = [];
    this._price = [];
    this._shopGoods.forEach(function(goods) {
        var item = null;
        switch (goods[0]) {
        case 0:
            item = $dataItems[goods[1]];
            break;
        case 1:
            item = $dataWeapons[goods[1]];
            break;
        case 2:
            item = $dataArmors[goods[1]];
            break;
        }
        if (item) {
            this._data.push(item);
            this._price.push(goods[2] === 0 ? item.price : goods[3]);
        }
    }, this);
};

/* 绘制项目 */
Window_ShopBuy.prototype.drawItem = function(index) {
    var item = this._data[index];
    var rect = this.itemRect(index);
    var priceWidth = 96;
    rect.width -= this.textPadding();
    this.changePaintOpacity(this.isEnabled(item));
    this.drawItemName(item, rect.x, rect.y, rect.width - priceWidth);
    this.drawText(this.price(item), rect.x + rect.width - priceWidth,
                  rect.y, priceWidth, 'right');
    this.changePaintOpacity(true);
};

/* 设置状态窗口 */
Window_ShopBuy.prototype.setStatusWindow = function(statusWindow) {
    this._statusWindow = statusWindow;
    this.callUpdateHelp();
};

/* 更新帮助 */
Window_ShopBuy.prototype.updateHelp = function() {
    this.setHelpWindowItem(this.item());
    if (this._statusWindow) {
        this._statusWindow.setItem(this.item());
    }
};

//-----------------------------------------------------------------------------
// 窗口_商店出售 
// Window_ShopSell
//
// 在商店画面上的选择要出售的商品的窗口。 
// The window for selecting an item to sell on the shop screen.

function Window_ShopSell() {
    this.initialize.apply(this, arguments);
}

Window_ShopSell.prototype = Object.create(Window_ItemList.prototype);
Window_ShopSell.prototype.constructor = Window_ShopSell;

/* 初始化 */
Window_ShopSell.prototype.initialize = function(x, y, width, height) {
    Window_ItemList.prototype.initialize.call(this, x, y, width, height);
};

/* 是否启用 */
Window_ShopSell.prototype.isEnabled = function(item) {
    return item &amp;&amp; item.price &gt; 0;
};

//-----------------------------------------------------------------------------
// 窗口_商店数值 
// Window_ShopNumber
//
// 在商店画面上的输入要买卖的商品数量的窗口。 
// The window for inputting quantity of items to buy or sell on the shop
// screen.

function Window_ShopNumber() {
    this.initialize.apply(this, arguments);
}

Window_ShopNumber.prototype = Object.create(Window_Selectable.prototype);
Window_ShopNumber.prototype.constructor = Window_ShopNumber;

/* 初始化 */
Window_ShopNumber.prototype.initialize = function(x, y, height) {
    var width = this.windowWidth();
    Window_Selectable.prototype.initialize.call(this, x, y, width, height);
    this._item = null;
    this._max = 1;
    this._price = 0;
    this._number = 1;
    this._currencyUnit = TextManager.currencyUnit;
    this.createButtons();
};

/* 窗口宽度 */
Window_ShopNumber.prototype.windowWidth = function() {
    return 456;
};

/* 数值 */
Window_ShopNumber.prototype.number = function() {
    return this._number;
};

/* 设置 */
Window_ShopNumber.prototype.setup = function(item, max, price) {
    this._item = item;
    this._max = Math.floor(max);
    this._price = price;
    this._number = 1;
    this.placeButtons();
    this.updateButtonsVisiblity();
    this.refresh();
};

/* 设置货币单位 */
Window_ShopNumber.prototype.setCurrencyUnit = function(currencyUnit) {
    this._currencyUnit = currencyUnit;
    this.refresh();
};

/* 创建按钮 */
Window_ShopNumber.prototype.createButtons = function() {
    var bitmap = ImageManager.loadSystem('ButtonSet');
    var buttonWidth = 48;
    var buttonHeight = 48;
    this._buttons = [];
    for (var i = 0; i &lt; 5; i) {
        var button = new Sprite_Button();
        var x = buttonWidth * i;
        var w = buttonWidth * (i === 4 ? 2 : 1);
        button.bitmap = bitmap;
        button.setColdFrame(x, 0, w, buttonHeight);
        button.setHotFrame(x, buttonHeight, w, buttonHeight);
        button.visible = false;
        this._buttons.push(button);
        this.addChild(button);
    }
    this._buttons[0].setClickHandler(this.onButtonDown2.bind(this));
    this._buttons[1].setClickHandler(this.onButtonDown.bind(this));
    this._buttons[2].setClickHandler(this.onButtonUp.bind(this));
    this._buttons[3].setClickHandler(this.onButtonUp2.bind(this));
    this._buttons[4].setClickHandler(this.onButtonOk.bind(this));
};

/* 放置按钮 */
Window_ShopNumber.prototype.placeButtons = function() {
    var numButtons = this._buttons.length;
    var spacing = 16;
    var totalWidth = -spacing;
    for (var i = 0; i &lt; numButtons; i) {
        totalWidth += this._buttons[i].width + spacing;
    }
    var x = (this.width - totalWidth) / 2;
    for (var j = 0; j &lt; numButtons; j) {
        var button = this._buttons[j];
        button.x = x;
        button.y = this.buttonY();
        x += button.width + spacing;
    }
};

/* 更新按钮可见性 */
Window_ShopNumber.prototype.updateButtonsVisiblity = function() {
    if (TouchInput.date &gt; Input.date) {
        this.showButtons();
    } else {
        this.hideButtons();
    }
};

/* 显示按钮 */
Window_ShopNumber.prototype.showButtons = function() {
    for (var i = 0; i &lt; this._buttons.length; i) {
        this._buttons[i].visible = true;
    }
};

/* 隐藏按钮 */
Window_ShopNumber.prototype.hideButtons = function() {
    for (var i = 0; i &lt; this._buttons.length; i) {
        this._buttons[i].visible = false;
    }
};

/* 刷新 */
Window_ShopNumber.prototype.refresh = function() {
    this.contents.clear();
    this.drawItemName(this._item, 0, this.itemY());
    this.drawMultiplicationSign();
    this.drawNumber();
    this.drawTotalPrice();
};

/* 绘制乘号 */
Window_ShopNumber.prototype.drawMultiplicationSign = function() {
    var sign = '\u00d7';
    var width = this.textWidth(sign);
    var x = this.cursorX() - width * 2;
    var y = this.itemY();
    this.resetTextColor();
    this.drawText(sign, x, y, width);
};

/* 绘制数值 */
Window_ShopNumber.prototype.drawNumber = function() {
    var x = this.cursorX();
    var y = this.itemY();
    var width = this.cursorWidth() - this.textPadding();
    this.resetTextColor();
    this.drawText(this._number, x, y, width, 'right');
};

/* 绘制总价 */
Window_ShopNumber.prototype.drawTotalPrice = function() {
    var total = this._price * this._number;
    var width = this.contentsWidth() - this.textPadding();
    this.drawCurrencyValue(total, this._currencyUnit, 0, this.priceY(), width);
};

/* 项目 Y 坐标 */
Window_ShopNumber.prototype.itemY = function() {
    return Math.round(this.contentsHeight() / 2 - this.lineHeight() * 1.5);
};

/* 价格 Y 坐标 */
Window_ShopNumber.prototype.priceY = function() {
    return Math.round(this.contentsHeight() / 2 + this.lineHeight() / 2);
};

/* 按钮 Y 坐标 */
Window_ShopNumber.prototype.buttonY = function() {
    return Math.round(this.priceY() + this.lineHeight() * 2.5);
};

/* 光标宽度 */
Window_ShopNumber.prototype.cursorWidth = function() {
    var digitWidth = this.textWidth('0');
    return this.maxDigits() * digitWidth + this.textPadding() * 2;
};

/* 光标 X 坐标 */
Window_ShopNumber.prototype.cursorX = function() {
    return this.contentsWidth() - this.cursorWidth() - this.textPadding();
};

/* 最大位数 */
Window_ShopNumber.prototype.maxDigits = function() {
    return 2;
};

/* 更新 */
Window_ShopNumber.prototype.update = function() {
    Window_Selectable.prototype.update.call(this);
    this.processNumberChange();
};

/* 是否确定触发 */
Window_ShopNumber.prototype.isOkTriggered = function() {
    return Input.isTriggered('ok');
};

/* 播放确定声音 */
Window_ShopNumber.prototype.playOkSound = function() {
};

/* 处理数值改变 */
Window_ShopNumber.prototype.processNumberChange = function() {
    if (this.isOpenAndActive()) {
        if (Input.isRepeated('right')) {
            this.changeNumber(1);
        }
        if (Input.isRepeated('left')) {
            this.changeNumber(-1);
        }
        if (Input.isRepeated('up')) {
            this.changeNumber(10);
        }
        if (Input.isRepeated('down')) {
            this.changeNumber(-10);
        }
    }
};

/* 改变数值 */
Window_ShopNumber.prototype.changeNumber = function(amount) {
    var lastNumber = this._number;
    this._number = (this._number + amount).clamp(1, this._max);
    if (this._number !== lastNumber) {
        SoundManager.playCursor();
        this.refresh();
    }
};

/* 更新光标 */
Window_ShopNumber.prototype.updateCursor = function() {
    this.setCursorRect(this.cursorX(), this.itemY(),
                       this.cursorWidth(), this.lineHeight());
};

/* 当按钮-向上 */
Window_ShopNumber.prototype.onButtonUp = function() {
    this.changeNumber(1);
};

/* 当按钮-向上 2 */
Window_ShopNumber.prototype.onButtonUp2 = function() {
    this.changeNumber(10);
};

/* 当按钮-向下 */
Window_ShopNumber.prototype.onButtonDown = function() {
    this.changeNumber(-1);
};

/* 当按钮-向下 2 */
Window_ShopNumber.prototype.onButtonDown2 = function() {
    this.changeNumber(-10);
};

/* 当按钮-确定 */
Window_ShopNumber.prototype.onButtonOk = function() {
    this.processOk();
};

//-----------------------------------------------------------------------------
// 窗口_商店状态 
// Window_ShopStatus
//
// 在商店画面上的显示物品持有数和角色装备的窗口。 
// The window for displaying number of items in possession and the actor's
// equipment on the shop screen.

function Window_ShopStatus() {
    this.initialize.apply(this, arguments);
}

Window_ShopStatus.prototype = Object.create(Window_Base.prototype);
Window_ShopStatus.prototype.constructor = Window_ShopStatus;

/* 初始化 */
Window_ShopStatus.prototype.initialize = function(x, y, width, height) {
    Window_Base.prototype.initialize.call(this, x, y, width, height);
    this._item = null;
    this._pageIndex = 0;
    this.refresh();
};

/* 刷新 */
Window_ShopStatus.prototype.refresh = function() {
    this.contents.clear();
    if (this._item) {
        var x = this.textPadding();
        this.drawPossession(x, 0);
        if (this.isEquipItem()) {
            this.drawEquipInfo(x, this.lineHeight() * 2);
        }
    }
};

/* 设置项目 */
Window_ShopStatus.prototype.setItem = function(item) {
    this._item = item;
    this.refresh();
};

/* 是否装备物品 */
Window_ShopStatus.prototype.isEquipItem = function() {
    return DataManager.isWeapon(this._item) || DataManager.isArmor(this._item);
};

/* 绘制持有数 */
Window_ShopStatus.prototype.drawPossession = function(x, y) {
    var width = this.contents.width - this.textPadding() - x;
    var possessionWidth = this.textWidth('0000');
    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.possession, x, y, width - possessionWidth);
    this.resetTextColor();
    this.drawText($gameParty.numItems(this._item), x, y, width, 'right');
};

/* 绘制装备信息 */
Window_ShopStatus.prototype.drawEquipInfo = function(x, y) {
    var members = this.statusMembers();
    for (var i = 0; i &lt; members.length; i) {
        this.drawActorEquipInfo(x, y + this.lineHeight() * (i * 2.4), members[i]);
    }
};

/* 状态成员 */
Window_ShopStatus.prototype.statusMembers = function() {
    var start = this._pageIndex * this.pageSize();
    var end = start + this.pageSize();
    return $gameParty.members().slice(start, end);
};

/* 页面大小 
 * 指一页显示几个成员的装备信息。 
 */
Window_ShopStatus.prototype.pageSize = function() {
    return 4;
};

/* 最大页数 */
Window_ShopStatus.prototype.maxPages = function() {
    return Math.floor(($gameParty.size() + this.pageSize() - 1) / this.pageSize());
};

/* 绘制角色装备信息 */
Window_ShopStatus.prototype.drawActorEquipInfo = function(x, y, actor) {
    var enabled = actor.canEquip(this._item);
    this.changePaintOpacity(enabled);
    this.resetTextColor();
    this.drawText(actor.name(), x, y, 168);
    var item1 = this.currentEquippedItem(actor, this._item.etypeId);
    if (enabled) {
        this.drawActorParamChange(x, y, actor, item1);
    }
    this.drawItemName(item1, x, y + this.lineHeight());
    this.changePaintOpacity(true);
};

/* 绘制角色能力值变化 */
Window_ShopStatus.prototype.drawActorParamChange = function(x, y, actor, item1) {
    var width = this.contents.width - this.textPadding() - x;
    var paramId = this.paramId();
    var change = this._item.params[paramId] - (item1 ? item1.params[paramId] : 0);
    this.changeTextColor(this.paramchangeTextColor(change));
    this.drawText((change &gt; 0 ? '+' : '') + change, x, y, width, 'right');
};

/* 能力值 ID */
Window_ShopStatus.prototype.paramId = function() {
    return DataManager.isWeapon(this._item) ? 2 : 3;
};

/* 当前装备的物品 */
Window_ShopStatus.prototype.currentEquippedItem = function(actor, etypeId) {
    var list = [];
    var equips = actor.equips();
    var slots = actor.equipSlots();
    for (var i = 0; i &lt; slots.length; i) {
        if (slots[i] === etypeId) {
            list.push(equips[i]);
        }
    }
    var paramId = this.paramId();
    var worstParam = Number.MAX_VALUE;
    var worstItem = null;
    for (var j = 0; j &lt; list.length; j) {
        if (list[j] &amp;&amp; list[j].params[paramId] &lt; worstParam) {
            worstParam = list[j].params[paramId];
            worstItem = list[j];
        }
    }
    return worstItem;
};

/* 更新 */
Window_ShopStatus.prototype.update = function() {
    Window_Base.prototype.update.call(this);
    this.updatePage();
};

/* 更新页面 */
Window_ShopStatus.prototype.updatePage = function() {
    if (this.isPageChangeEnabled() &amp;&amp; this.isPageChangeRequested()) {
        this.changePage();
    }
};

/* 是否页面更改启用 */
Window_ShopStatus.prototype.isPageChangeEnabled = function() {
    return this.visible &amp;&amp; this.maxPages() &gt;= 2;
};

/* 是否页面更改请求 */
Window_ShopStatus.prototype.isPageChangeRequested = function() {
    if (Input.isTriggered('shift')) {
        return true;
    }
    if (TouchInput.isTriggered() &amp;&amp; this.isTouchedInsideFrame()) {
        return true;
    }
    return false;
};

/* 是否触摸在内部框 */
Window_ShopStatus.prototype.isTouchedInsideFrame = function() {
    var x = this.canvasToLocalX(TouchInput.x);
    var y = this.canvasToLocalY(TouchInput.y);
    return x &gt;= 0 &amp;&amp; y &gt;= 0 &amp;&amp; x &lt; this.width &amp;&amp; y &lt; this.height;
};

/* 更改页面 */
Window_ShopStatus.prototype.changePage = function() {
    this._pageIndex = (this._pageIndex + 1) % this.maxPages();
    this.refresh();
    SoundManager.playCursor();
};

//-----------------------------------------------------------------------------
// 窗口_名字编辑 
// Window_NameEdit
//
// 在名字输入画面上的编辑角色名字的窗口。 
// The window for editing an actor's name on the name input screen.

function Window_NameEdit() {
    this.initialize.apply(this, arguments);
}

Window_NameEdit.prototype = Object.create(Window_Base.prototype);
Window_NameEdit.prototype.constructor = Window_NameEdit;

/* 初始化 */
Window_NameEdit.prototype.initialize = function(actor, maxLength) {
    var width = this.windowWidth();
    var height = this.windowHeight();
    var x = (Graphics.boxWidth - width) / 2;
    var y = (Graphics.boxHeight - (height + this.fittingHeight(9) + 8)) / 2;
    Window_Base.prototype.initialize.call(this, x, y, width, height);
    this._actor = actor;
    this._name = actor.name().slice(0, this._maxLength);
    this._index = this._name.length;
    this._maxLength = maxLength;
    this._defaultName = this._name;
    this.deactivate();
    this.refresh();
    ImageManager.reserveFace(actor.faceName());
};

/* 窗口宽度 */
Window_NameEdit.prototype.windowWidth = function() {
    return 480;
};

/* 窗口高度 */
Window_NameEdit.prototype.windowHeight = function() {
    return this.fittingHeight(4);
};

/* 名字 */
Window_NameEdit.prototype.name = function() {
    return this._name;
};

/* 恢复默认 */
Window_NameEdit.prototype.restoreDefault = function() {
    this._name = this._defaultName;
    this._index = this._name.length;
    this.refresh();
    return this._name.length &gt; 0;
};

/* 增加 */
Window_NameEdit.prototype.add = function(ch) {
    if (this._index &lt; this._maxLength) {
        this._name += ch;
        this._index;
        this.refresh();
        return true;
    } else {
        return false;
    }
};

/* 回退 */
Window_NameEdit.prototype.back = function() {
    if (this._index &gt; 0) {
        this._index--;
        this._name = this._name.slice(0, this._index);
        this.refresh();
        return true;
    } else {
        return false;
    }
};

/* 脸图宽度 */
Window_NameEdit.prototype.faceWidth = function() {
    return 144;
};

/* 字符宽度 */
Window_NameEdit.prototype.charWidth = function() {
    var text = $gameSystem.isJapanese() ? '\uff21' : 'A';
    return this.textWidth(text);
};

/* 左边 */
Window_NameEdit.prototype.left = function() {
    var nameCenter = (this.contentsWidth() + this.faceWidth()) / 2;
    var nameWidth = (this._maxLength + 1) * this.charWidth();
    return Math.min(nameCenter - nameWidth / 2, this.contentsWidth() - nameWidth);
};

/* 项目矩形区域 */
Window_NameEdit.prototype.itemRect = function(index) {
    return {
        x: this.left() + index * this.charWidth(),
        y: 54,
        width: this.charWidth(),
        height: this.lineHeight()
    };
};

/* 下划线矩形区域 */
Window_NameEdit.prototype.underlineRect = function(index) {
    var rect = this.itemRect(index);
    rect.x;
    rect.y += rect.height - 4;
    rect.width -= 2;
    rect.height = 2;
    return rect;
};

/* 下划线颜色 */
Window_NameEdit.prototype.underlineColor = function() {
    return this.normalColor();
};

/* 绘制下划线 */
Window_NameEdit.prototype.drawUnderline = function(index) {
    var rect = this.underlineRect(index);
    var color = this.underlineColor();
    this.contents.paintOpacity = 48;
    this.contents.fillRect(rect.x, rect.y, rect.width, rect.height, color);
    this.contents.paintOpacity = 255;
};

/* 绘制字符 */
Window_NameEdit.prototype.drawChar = function(index) {
    var rect = this.itemRect(index);
    this.resetTextColor();
    this.drawText(this._name[index] || '', rect.x, rect.y);
};

/* 刷新 */
Window_NameEdit.prototype.refresh = function() {
    this.contents.clear();
    this.drawActorFace(this._actor, 0, 0);
    for (var i = 0; i &lt; this._maxLength; i) {
        this.drawUnderline(i);
    }
    for (var j = 0; j &lt; this._name.length; j) {
        this.drawChar(j);
    }
    var rect = this.itemRect(this._index);
    this.setCursorRect(rect.x, rect.y, rect.width, rect.height);
};

//-----------------------------------------------------------------------------
// 窗口_名字输入 
// Window_NameInput
//
// 在名字输入画面上的选择文本字符的窗口。 
// The window for selecting text characters on the name input screen.

function Window_NameInput() {
    this.initialize.apply(this, arguments);
}

Window_NameInput.prototype = Object.create(Window_Selectable.prototype);
Window_NameInput.prototype.constructor = Window_NameInput;
Window_NameInput.LATIN1 =
        [ 'A','B','C','D','E',  'a','b','c','d','e',
          'F','G','H','I','J',  'f','g','h','i','j',
          'K','L','M','N','O',  'k','l','m','n','o',
          'P','Q','R','S','T',  'p','q','r','s','t',
          'U','V','W','X','Y',  'u','v','w','x','y',
          'Z','[',']','^','_',  'z','{','}','|','~',
          '0','1','2','3','4',  '!','#','$','%','&amp;',
          '5','6','7','8','9',  '(',')','*','+','-',
          '/','=','@','&lt;','&gt;',  ':',';',' ','Page','OK' ];  // 拉丁文 1 
Window_NameInput.LATIN2 =
        [ 'Á','É','Í','Ó','Ú',  'á','é','í','ó','ú',
          'À','È','Ì','Ò','Ù',  'à','è','ì','ò','ù',
          'Â','Ê','Î','Ô','Û',  'â','ê','î','ô','û',
          'Ä','Ë','Ï','Ö','Ü',  'ä','ë','ï','ö','ü',
          'Ā','Ē','Ī','Ō','Ū',  'ā','ē','ī','ō','ū',
          'Ã','Å','Æ','Ç','Ð',  'ã','å','æ','ç','ð',
          'Ñ','Õ','Ø','Š','Ŵ',  'ñ','õ','ø','š','ŵ',
          'Ý','Ŷ','Ÿ','Ž','Þ',  'ý','ÿ','ŷ','ž','þ',
          'Ĳ','Œ','ĳ','œ','ß',  '«','»',' ','Page','OK' ];  // 拉丁文 2 
Window_NameInput.RUSSIA =
        [ 'А','Б','В','Г','Д',  'а','б','в','г','д',
          'Е','Ё','Ж','З','И',  'е','ё','ж','з','и',
          'Й','К','Л','М','Н',  'й','к','л','м','н',
          'О','П','Р','С','Т',  'о','п','р','с','т',
          'У','Ф','Х','Ц','Ч',  'у','ф','х','ц','ч',
          'Ш','Щ','Ъ','Ы','Ь',  'ш','щ','ъ','ы','ь',
          'Э','Ю','Я','^','_',  'э','ю','я','%','&amp;',
          '0','1','2','3','4',  '(',')','*','+','-',
          '5','6','7','8','9',  ':',';',' ','','OK' ];  // 俄文 
Window_NameInput.JAPAN1 =
        [ 'あ','い','う','え','お',  'が','ぎ','ぐ','げ','ご',
          'か','き','く','け','こ',  'ざ','じ','ず','ぜ','ぞ',
          'さ','し','す','せ','そ',  'だ','ぢ','づ','で','ど',
          'た','ち','つ','て','と',  'ば','び','ぶ','べ','ぼ',
          'な','に','ぬ','ね','の',  'ぱ','ぴ','ぷ','ぺ','ぽ',
          'は','ひ','ふ','へ','ほ',  'ぁ','ぃ','ぅ','ぇ','ぉ',
          'ま','み','む','め','も',  'っ','ゃ','ゅ','ょ','ゎ',
          'や','ゆ','よ','わ','ん',  'ー','～','・','＝','☆',
          'ら','り','る','れ','ろ',  'ゔ','を','　','カナ','決定' ];  // 日文 1 
Window_NameInput.JAPAN2 =
        [ 'ア','イ','ウ','エ','オ',  'ガ','ギ','グ','ゲ','ゴ',
          'カ','キ','ク','ケ','コ',  'ザ','ジ','ズ','ゼ','ゾ',
          'サ','シ','ス','セ','ソ',  'ダ','ヂ','ヅ','デ','ド',
          'タ','チ','ツ','テ','ト',  'バ','ビ','ブ','ベ','ボ',
          'ナ','ニ','ヌ','ネ','ノ',  'パ','ピ','プ','ペ','ポ',
          'ハ','ヒ','フ','ヘ','ホ',  'ァ','ィ','ゥ','ェ','ォ',
          'マ','ミ','ム','メ','モ',  'ッ','ャ','ュ','ョ','ヮ',
          'ヤ','ユ','ヨ','ワ','ン',  'ー','～','・','＝','☆',
          'ラ','リ','ル','レ','ロ',  'ヴ','ヲ','　','英数','決定' ]; // 日文 2
Window_NameInput.JAPAN3 =
        [ 'Ａ','Ｂ','Ｃ','Ｄ','Ｅ',  'ａ','ｂ','ｃ','ｄ','ｅ',
          'Ｆ','Ｇ','Ｈ','Ｉ','Ｊ',  'ｆ','ｇ','ｈ','ｉ','ｊ',
          'Ｋ','Ｌ','Ｍ','Ｎ','Ｏ',  'ｋ','ｌ','ｍ','ｎ','ｏ',
          'Ｐ','Ｑ','Ｒ','Ｓ','Ｔ',  'ｐ','ｑ','ｒ','ｓ','ｔ',
          'Ｕ','Ｖ','Ｗ','Ｘ','Ｙ',  'ｕ','ｖ','ｗ','ｘ','ｙ',
          'Ｚ','［','］','＾','＿',  'ｚ','｛','｝','｜','～',
          '０','１','２','３','４',  '！','＃','＄','％','＆',
          '５','６','７','８','９',  '（','）','＊','＋','－',
          '／','＝','＠','＜','＞',  '：','；','　','かな','決定' ];  // 日文 3 

/* 初始化 */
Window_NameInput.prototype.initialize = function(editWindow) {
    var x = editWindow.x;
    var y = editWindow.y + editWindow.height + 8;
    var width = editWindow.width;
    var height = this.windowHeight();
    Window_Selectable.prototype.initialize.call(this, x, y, width, height);
    this._editWindow = editWindow;
    this._page = 0;
    this._index = 0;
    this.refresh();
    this.updateCursor();
    this.activate();
};

/* 窗口宽度 */
Window_NameInput.prototype.windowHeight = function() {
    return this.fittingHeight(9);
};

/* 表 */
Window_NameInput.prototype.table = function() {
    if ($gameSystem.isJapanese()) {
        return [Window_NameInput.JAPAN1,
                Window_NameInput.JAPAN2,
                Window_NameInput.JAPAN3];
    } else if ($gameSystem.isRussian()) {
        return [Window_NameInput.RUSSIA];
    } else {
        return [Window_NameInput.LATIN1,
                Window_NameInput.LATIN2];
    }
};

/* 最大列数 */
Window_NameInput.prototype.maxCols = function() {
    return 10;
};

/* 最大项目数 */
Window_NameInput.prototype.maxItems = function() {
    return 90;
};

/* 字符 */
Window_NameInput.prototype.character = function() {
    return this._index &lt; 88 ? this.table()[this._page][this._index] : '';
};

/* 是否页面切换 */
Window_NameInput.prototype.isPageChange = function() {
    return this._index === 88;
};

/* 是否确定 */
Window_NameInput.prototype.isOk = function() {
    return this._index === 89;
};

/* 项目矩形区域 */
Window_NameInput.prototype.itemRect = function(index) {
    return {
        x: index % 10 * 42 + Math.floor(index % 10 / 5) * 24,
        y: Math.floor(index / 10) * this.lineHeight(),
        width: 42,
        height: this.lineHeight()
    };
};

/* 刷新 */
Window_NameInput.prototype.refresh = function() {
    var table = this.table();
    this.contents.clear();
    this.resetTextColor();
    for (var i = 0; i &lt; 90; i) {
        var rect = this.itemRect(i);
        rect.x += 3;
        rect.width -= 6;
        this.drawText(table[this._page][i], rect.x, rect.y, rect.width, 'center');
    }
};

/* 更新光标 */
Window_NameInput.prototype.updateCursor = function() {
    var rect = this.itemRect(this._index);
    this.setCursorRect(rect.x, rect.y, rect.width, rect.height);
};

/* 是否光标可移动 */
Window_NameInput.prototype.isCursorMovable = function() {
    return this.active;
};

/* 光标向下 */
Window_NameInput.prototype.cursorDown = function(wrap) {
    if (this._index &lt; 80 || wrap) {
        this._index = (this._index + 10) % 90;
    }
};

/* 光标向上 */
Window_NameInput.prototype.cursorUp = function(wrap) {
    if (this._index &gt;= 10 || wrap) {
        this._index = (this._index + 80) % 90;
    }
};

/* 光标向右 */
Window_NameInput.prototype.cursorRight = function(wrap) {
    if (this._index % 10 &lt; 9) {
        this._index;
    } else if (wrap) {
        this._index -= 9;
    }
};

/* 光标向左 */
Window_NameInput.prototype.cursorLeft = function(wrap) {
    if (this._index % 10 &gt; 0) {
        this._index--;
    } else if (wrap) {
        this._index += 9;
    }
};

/* 光标下翻页 */
Window_NameInput.prototype.cursorPagedown = function() {
    this._page = (this._page + 1) % this.table().length;
    this.refresh();
};

/* 光标上翻页 */
Window_NameInput.prototype.cursorPageup = function() {
    this._page = (this._page + this.table().length - 1) % this.table().length;
    this.refresh();
};

/* 处理光标移 */
Window_NameInput.prototype.processCursorMove = function() {
    var lastPage = this._page;
    Window_Selectable.prototype.processCursorMove.call(this);
    this.updateCursor();
    if (this._page !== lastPage) {
        SoundManager.playCursor();
    }
};

/* 处理处理 */
Window_NameInput.prototype.processHandling = function() {
    if (this.isOpen() &amp;&amp; this.active) {
        if (Input.isTriggered('shift')) {
            this.processJump();
        }
        if (Input.isRepeated('cancel')) {
            this.processBack();
        }
        if (Input.isRepeated('ok')) {
            this.processOk();
        }
    }
};

/* 是否取消启用 */
Window_NameInput.prototype.isCancelEnabled = function() {
    return true;
};

/* 处理取消 */
Window_NameInput.prototype.processCancel = function() {
    this.processBack();
};

/* 处理跳转 
 * 光标跳转到 OK 处。 
 */
Window_NameInput.prototype.processJump = function() {
    if (this._index !== 89) {
        this._index = 89;
        SoundManager.playCursor();
    }
};

/* 处理回退 */
Window_NameInput.prototype.processBack = function() {
    if (this._editWindow.back()) {
        SoundManager.playCancel();
    }
};

/* 处理确定 */
Window_NameInput.prototype.processOk = function() {
    if (this.character()) {
        this.onNameAdd();
    } else if (this.isPageChange()) {
        SoundManager.playOk();
        this.cursorPagedown();
    } else if (this.isOk()) {
        this.onNameOk();
    }
};

/* 当名字增加 */
Window_NameInput.prototype.onNameAdd = function() {
    if (this._editWindow.add(this.character())) {
        SoundManager.playOk();
    } else {
        SoundManager.playBuzzer();
    }
};

/* 当名字确定 */
Window_NameInput.prototype.onNameOk = function() {
    if (this._editWindow.name() === '') {
        if (this._editWindow.restoreDefault()) {
            SoundManager.playOk();
        } else {
            SoundManager.playBuzzer();
        }
    } else {
        SoundManager.playOk();
        this.callOkHandler();
    }
};

//-----------------------------------------------------------------------------
// 窗口_选项列表 
// Window_ChoiceList
//
// 用于事件指令[显示选项]的窗口。 
// The window used for the event command [Show Choices].

function Window_ChoiceList() {
    this.initialize.apply(this, arguments);
}

Window_ChoiceList.prototype = Object.create(Window_Command.prototype);
Window_ChoiceList.prototype.constructor = Window_ChoiceList;

/* 初始化 */
Window_ChoiceList.prototype.initialize = function(messageWindow) {
    this._messageWindow = messageWindow;
    Window_Command.prototype.initialize.call(this, 0, 0);
    this.openness = 0;
    this.deactivate();
    this._background = 0;
};

/* 开始 */
Window_ChoiceList.prototype.start = function() {
    this.updatePlacement();
    this.updateBackground();
    this.refresh();
    this.selectDefault();
    this.open();
    this.activate();
};

/* 选择默认 */
Window_ChoiceList.prototype.selectDefault = function() {
    this.select($gameMessage.choiceDefaultType());
};

/* 更新位置 */
Window_ChoiceList.prototype.updatePlacement = function() {
    var positionType = $gameMessage.choicePositionType();
    var messageY = this._messageWindow.y;
    this.width = this.windowWidth();
    this.height = this.windowHeight();
    switch (positionType) {
    case 0:
        this.x = 0;
        break;
    case 1:
        this.x = (Graphics.boxWidth - this.width) / 2;
        break;
    case 2:
        this.x = Graphics.boxWidth - this.width;
        break;
    }
    if (messageY &gt;= Graphics.boxHeight / 2) {
        this.y = messageY - this.height;
    } else {
        this.y = messageY + this._messageWindow.height;
    }
};

/* 更新背景 */
Window_ChoiceList.prototype.updateBackground = function() {
    this._background = $gameMessage.choiceBackground();
    this.setBackgroundType(this._background);
};

/* 窗口宽度 */
Window_ChoiceList.prototype.windowWidth = function() {
    var width = this.maxChoiceWidth() + this.padding * 2;
    return Math.min(width, Graphics.boxWidth);
};

/* 可见的行数 */
Window_ChoiceList.prototype.numVisibleRows = function() {
    var messageY = this._messageWindow.y;
    var messageHeight = this._messageWindow.height;
    var centerY = Graphics.boxHeight / 2;
    var choices = $gameMessage.choices();
    var numLines = choices.length;
    var maxLines = 8;
    if (messageY &lt; centerY &amp;&amp; messageY + messageHeight &gt; centerY) {
        maxLines = 4;
    }
    if (numLines &gt; maxLines) {
        numLines = maxLines;
    }
    return numLines;
};

/* 最大选项宽度 */
Window_ChoiceList.prototype.maxChoiceWidth = function() {
    var maxWidth = 96;
    var choices = $gameMessage.choices();
    for (var i = 0; i &lt; choices.length; i) {
        var choiceWidth = this.textWidthEx(choices[i]) + this.textPadding() * 2;
        if (maxWidth &lt; choiceWidth) {
            maxWidth = choiceWidth;
        }
    }
    return maxWidth;
};

/* 文本宽扩展 */
Window_ChoiceList.prototype.textWidthEx = function(text) {
    return this.drawTextEx(text, 0, this.contents.height);
};

/* 内容高度 */
Window_ChoiceList.prototype.contentsHeight = function() {
    return this.maxItems() * this.itemHeight();
};

/* 制作指令列表 */
Window_ChoiceList.prototype.makeCommandList = function() {
    var choices = $gameMessage.choices();
    for (var i = 0; i &lt; choices.length; i) {
        this.addCommand(choices[i], 'choice');
    }
};

/* 绘制项目 */
Window_ChoiceList.prototype.drawItem = function(index) {
    var rect = this.itemRectForText(index);
    this.drawTextEx(this.commandName(index), rect.x, rect.y);
};

/* 是否取消启用 */
Window_ChoiceList.prototype.isCancelEnabled = function() {
    return $gameMessage.choiceCancelType() !== -1;
};

/* 是否确定触发 */
Window_ChoiceList.prototype.isOkTriggered = function() {
    return Input.isTriggered('ok');
};

/* 呼叫确定处理者 */
Window_ChoiceList.prototype.callOkHandler = function() {
    $gameMessage.onChoice(this.index());
    this._messageWindow.terminateMessage();
    this.close();
};

/* 呼叫取消处理者 */
Window_ChoiceList.prototype.callCancelHandler = function() {
    $gameMessage.onChoice($gameMessage.choiceCancelType());
    this._messageWindow.terminateMessage();
    this.close();
};

//-----------------------------------------------------------------------------
// 窗口_数值输入 
// Window_NumberInput
//
// 用于事件指令[数值输入处理]的窗口。 
// The window used for the event command [Input Number].

function Window_NumberInput() {
    this.initialize.apply(this, arguments);
}

Window_NumberInput.prototype = Object.create(Window_Selectable.prototype);
Window_NumberInput.prototype.constructor = Window_NumberInput;

/* 初始化 */
Window_NumberInput.prototype.initialize = function(messageWindow) {
    this._messageWindow = messageWindow;
    Window_Selectable.prototype.initialize.call(this, 0, 0, 0, 0);
    this._number = 0;
    this._maxDigits = 1;
    this.openness = 0;
    this.createButtons();
    this.deactivate();
};

/* 开始 */
Window_NumberInput.prototype.start = function() {
    this._maxDigits = $gameMessage.numInputMaxDigits();
    this._number = $gameVariables.value($gameMessage.numInputVariableId());
    this._number = this._number.clamp(0, Math.pow(10, this._maxDigits) - 1);
    this.updatePlacement();
    this.placeButtons();
    this.updateButtonsVisiblity();
    this.createContents();
    this.refresh();
    this.open();
    this.activate();
    this.select(0);
};

/* 更新位置 */
Window_NumberInput.prototype.updatePlacement = function() {
    var messageY = this._messageWindow.y;
    var spacing = 8;
    this.width = this.windowWidth();
    this.height = this.windowHeight();
    this.x = (Graphics.boxWidth - this.width) / 2;
    if (messageY &gt;= Graphics.boxHeight / 2) {
        this.y = messageY - this.height - spacing;
    } else {
        this.y = messageY + this._messageWindow.height + spacing;
    }
};

/* 窗口宽度 */
Window_NumberInput.prototype.windowWidth = function() {
    return this.maxCols() * this.itemWidth() + this.padding * 2;
};

/* 窗口高度 */
Window_NumberInput.prototype.windowHeight = function() {
    return this.fittingHeight(1);
};

/* 最大列数 */
Window_NumberInput.prototype.maxCols = function() {
    return this._maxDigits;
};

/* 最大项目数 */
Window_NumberInput.prototype.maxItems = function() {
    return this._maxDigits;
};

/* 间距 */
Window_NumberInput.prototype.spacing = function() {
    return 0;
};

/* 项目宽度 */
Window_NumberInput.prototype.itemWidth = function() {
    return 32;
};

/* 创建按钮 */
Window_NumberInput.prototype.createButtons = function() {
    var bitmap = ImageManager.loadSystem('ButtonSet');
    var buttonWidth = 48;
    var buttonHeight = 48;
    this._buttons = [];
    for (var i = 0; i &lt; 3; i) {
        var button = new Sprite_Button();
        var x = buttonWidth * [1, 2, 4][i];
        var w = buttonWidth * (i === 2 ? 2 : 1);
        button.bitmap = bitmap;
        button.setColdFrame(x, 0, w, buttonHeight);
        button.setHotFrame(x, buttonHeight, w, buttonHeight);
        button.visible = false;
        this._buttons.push(button);
        this.addChild(button);
    }
    this._buttons[0].setClickHandler(this.onButtonDown.bind(this));
    this._buttons[1].setClickHandler(this.onButtonUp.bind(this));
    this._buttons[2].setClickHandler(this.onButtonOk.bind(this));
};

/* 放置按钮 */
Window_NumberInput.prototype.placeButtons = function() {
    var numButtons = this._buttons.length;
    var spacing = 16;
    var totalWidth = -spacing;
    for (var i = 0; i &lt; numButtons; i) {
        totalWidth += this._buttons[i].width + spacing;
    }
    var x = (this.width - totalWidth) / 2;
    for (var j = 0; j &lt; numButtons; j) {
        var button = this._buttons[j];
        button.x = x;
        button.y = this.buttonY();
        x += button.width + spacing;
    }
};

/* 更新按钮可见性 */
Window_NumberInput.prototype.updateButtonsVisiblity = function() {
    if (TouchInput.date &gt; Input.date) {
        this.showButtons();
    } else {
        this.hideButtons();
    }
};

/* 显示按钮 */
Window_NumberInput.prototype.showButtons = function() {
    for (var i = 0; i &lt; this._buttons.length; i) {
        this._buttons[i].visible = true;
    }
};

/* 隐藏按钮 */
Window_NumberInput.prototype.hideButtons = function() {
    for (var i = 0; i &lt; this._buttons.length; i) {
        this._buttons[i].visible = false;
    }
};

/* 按钮 Y 坐标 */
Window_NumberInput.prototype.buttonY = function() {
    var spacing = 8;
    if (this._messageWindow.y &gt;= Graphics.boxHeight / 2) {
        return 0 - this._buttons[0].height - spacing;
    } else {
        return this.height + spacing;
    }
};

/* 更新 */
Window_NumberInput.prototype.update = function() {
    Window_Selectable.prototype.update.call(this);
    this.processDigitChange();
};

/* 处理数字改变 */
Window_NumberInput.prototype.processDigitChange = function() {
    if (this.isOpenAndActive()) {
        if (Input.isRepeated('up')) {
            this.changeDigit(true);
        } else if (Input.isRepeated('down')) {
            this.changeDigit(false);
        }
    }
};

/* 改变数字 */
Window_NumberInput.prototype.changeDigit = function(up) {
    var index = this.index();
    var place = Math.pow(10, this._maxDigits - 1 - index);
    var n = Math.floor(this._number / place) % 10;
    this._number -= n * place;
    if (up) {
        n = (n + 1) % 10;
    } else {
        n = (n + 9) % 10;
    }
    this._number += n * place;
    this.refresh();
    SoundManager.playCursor();
};

/* 是否触摸确定启用 */
Window_NumberInput.prototype.isTouchOkEnabled = function() {
    return false;
};

/* 是否确定启用 */
Window_NumberInput.prototype.isOkEnabled = function() {
    return true;
};

/* 是否取消启用 */
Window_NumberInput.prototype.isCancelEnabled = function() {
    return false;
};

/* 是否确定触发 */
Window_NumberInput.prototype.isOkTriggered = function() {
    return Input.isTriggered('ok');
};

/* 处理确定 */
Window_NumberInput.prototype.processOk = function() {
    SoundManager.playOk();
    $gameVariables.setValue($gameMessage.numInputVariableId(), this._number);
    this._messageWindow.terminateMessage();
    this.updateInputData();
    this.deactivate();
    this.close();
};

/* 绘制项目 */
Window_NumberInput.prototype.drawItem = function(index) {
    var rect = this.itemRect(index);
    var align = 'center';
    var s = this._number.padZero(this._maxDigits);
    var c = s.slice(index, index + 1);
    this.resetTextColor();
    this.drawText(c, rect.x, rect.y, rect.width, align);
};

/* 当按钮-向上 */
Window_NumberInput.prototype.onButtonUp = function() {
    this.changeDigit(true);
};

/* 当按钮-向下 */
Window_NumberInput.prototype.onButtonDown = function() {
    this.changeDigit(false);
};

/* 当按钮-确定 */
Window_NumberInput.prototype.onButtonOk = function() {
    this.processOk();
    this.hideButtons();
};

//-----------------------------------------------------------------------------
// 窗口_事件物品 
// Window_EventItem
//
// 用于事件指令[物品选择处理]的窗口。 
// The window used for the event command [Select Item].

function Window_EventItem() {
    this.initialize.apply(this, arguments);
}

Window_EventItem.prototype = Object.create(Window_ItemList.prototype);
Window_EventItem.prototype.constructor = Window_EventItem;

/* 初始化 */
Window_EventItem.prototype.initialize = function(messageWindow) {
    this._messageWindow = messageWindow;
    var width = Graphics.boxWidth;
    var height = this.windowHeight();
    Window_ItemList.prototype.initialize.call(this, 0, 0, width, height);
    this.openness = 0;
    this.deactivate();
    this.setHandler('ok',     this.onOk.bind(this));
    this.setHandler('cancel', this.onCancel.bind(this));
};

/* 窗口高度 */
Window_EventItem.prototype.windowHeight = function() {
    return this.fittingHeight(this.numVisibleRows());
};

/* 可见的行数 */
Window_EventItem.prototype.numVisibleRows = function() {
    return 4;
};

/* 开始 */
Window_EventItem.prototype.start = function() {
    this.refresh();
    this.updatePlacement();
    this.select(0);
    this.open();
    this.activate();
};

/* 更新位置 */
Window_EventItem.prototype.updatePlacement = function() {
    if (this._messageWindow.y &gt;= Graphics.boxHeight / 2) {
        this.y = 0;
    } else {
        this.y = Graphics.boxHeight - this.height;
    }
};

/* 包含 */
Window_EventItem.prototype.includes = function(item) {
    var itypeId = $gameMessage.itemChoiceItypeId();
    return DataManager.isItem(item) &amp;&amp; item.itypeId === itypeId;
};

/* 是否启用 */
Window_EventItem.prototype.isEnabled = function(item) {
    return true;
};

/* 当确定 */
Window_EventItem.prototype.onOk = function() {
    var item = this.item();
    var itemId = item ? item.id : 0;
    $gameVariables.setValue($gameMessage.itemChoiceVariableId(), itemId);
    this._messageWindow.terminateMessage();
    this.close();
};

/* 当取消 */
Window_EventItem.prototype.onCancel = function() {
    $gameVariables.setValue($gameMessage.itemChoiceVariableId(), 0);
    this._messageWindow.terminateMessage();
    this.close();
};

//-----------------------------------------------------------------------------
// 窗口_信息 
// Window_Message
//
// 显示文本信息的窗口。 
// The window for displaying text messages.

function Window_Message() {
    this.initialize.apply(this, arguments);
}

Window_Message.prototype = Object.create(Window_Base.prototype);
Window_Message.prototype.constructor = Window_Message;

/* 初始化 */
Window_Message.prototype.initialize = function() {
    var width = this.windowWidth();
    var height = this.windowHeight();
    var x = (Graphics.boxWidth - width) / 2;
    Window_Base.prototype.initialize.call(this, x, 0, width, height);
    this.openness = 0;
    this.initMembers();
    this.createSubWindows();
    this.updatePlacement();
};

/* 初始化成员 */
Window_Message.prototype.initMembers = function() {
    this._imageReservationId = Utils.generateRuntimeId();
    this._background = 0;
    this._positionType = 2;
    this._waitCount = 0;
    this._faceBitmap = null;
    this._textState = null;
    this.clearFlags();
};

/* 子窗口 */
Window_Message.prototype.subWindows = function() {
    return [this._goldWindow, this._choiceWindow,
            this._numberWindow, this._itemWindow];
};

/* 创建子窗口 */
Window_Message.prototype.createSubWindows = function() {
    this._goldWindow = new Window_Gold(0, 0);
    this._goldWindow.x = Graphics.boxWidth - this._goldWindow.width;
    this._goldWindow.openness = 0;
    this._choiceWindow = new Window_ChoiceList(this);
    this._numberWindow = new Window_NumberInput(this);
    this._itemWindow = new Window_EventItem(this);
};

/* 窗口宽度 */
Window_Message.prototype.windowWidth = function() {
    return Graphics.boxWidth;
};

/* 窗口高度 */
Window_Message.prototype.windowHeight = function() {
    return this.fittingHeight(this.numVisibleRows());
};

/* 清除标志 */
Window_Message.prototype.clearFlags = function() {
    this._showFast = false;
    this._lineShowFast = false;
    this._pauseSkip = false;
};

/* 可见的行数 */
Window_Message.prototype.numVisibleRows = function() {
    return 4;
};

/* 更新 */
Window_Message.prototype.update = function() {
    this.checkToNotClose();
    Window_Base.prototype.update.call(this);
    while (!this.isOpening() &amp;&amp; !this.isClosing()) {
        if (this.updateWait()) {
            return;
        } else if (this.updateLoading()) {
            return;
        } else if (this.updateInput()) {
            return;
        } else if (this.updateMessage()) {
            return;
        } else if (this.canStart()) {
            this.startMessage();
        } else {
            this.startInput();
            return;
        }
    }
};

/* 检测不关闭 */
Window_Message.prototype.checkToNotClose = function() {
    if (this.isClosing() &amp;&amp; this.isOpen()) {
        if (this.doesContinue()) {
            this.open();
        }
    }
};

/* 是否能开始 */
Window_Message.prototype.canStart = function() {
    return $gameMessage.hasText() &amp;&amp; !$gameMessage.scrollMode();
};

/* 开始信息 */
Window_Message.prototype.startMessage = function() {
    this._textState = {};
    this._textState.index = 0;
    this._textState.text = this.convertEscapeCharacters($gameMessage.allText());
    this.newPage(this._textState);
    this.updatePlacement();
    this.updateBackground();
    this.open();
};

/* 更新位置 */
Window_Message.prototype.updatePlacement = function() {
    this._positionType = $gameMessage.positionType();
    this.y = this._positionType * (Graphics.boxHeight - this.height) / 2;
    this._goldWindow.y = this.y &gt; 0 ? 0 : Graphics.boxHeight - this._goldWindow.height;
};

/* 更新背景 */
Window_Message.prototype.updateBackground = function() {
    this._background = $gameMessage.background();
    this.setBackgroundType(this._background);
};

/* 结束信息 */
Window_Message.prototype.terminateMessage = function() {
    this.close();
    this._goldWindow.close();
    $gameMessage.clear();
};

/* 更新等待 */
Window_Message.prototype.updateWait = function() {
    if (this._waitCount &gt; 0) {
        this._waitCount--;
        return true;
    } else {
        return false;
    }
};

/* 更新加载中 */
Window_Message.prototype.updateLoading = function() {
    if (this._faceBitmap) {
        if (this._faceBitmap.isReady()) {
            this.drawMessageFace();
            this._faceBitmap = null;
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
};

/* 更新输入 */
Window_Message.prototype.updateInput = function() {
    if (this.isAnySubWindowActive()) {
        return true;
    }
    if (this.pause) {
        if (this.isTriggered()) {
            Input.update();
            this.pause = false;
            if (!this._textState) {
                this.terminateMessage();
            }
        }
        return true;
    }
    return false;
};

/* 是否有任何子窗口处于活动状态 */
Window_Message.prototype.isAnySubWindowActive = function() {
    return (this._choiceWindow.active ||
            this._numberWindow.active ||
            this._itemWindow.active);
};

/* 更新信息 */
Window_Message.prototype.updateMessage = function() {
    if (this._textState) {
        while (!this.isEndOfText(this._textState)) {
            if (this.needsNewPage(this._textState)) {
                this.newPage(this._textState);
            }
            this.updateShowFast();
            this.processCharacter(this._textState);
            if (!this._showFast &amp;&amp; !this._lineShowFast) {
                break;
            }
            if (this.pause || this._waitCount &gt; 0) {
                break;
            }
        }
        if (this.isEndOfText(this._textState)) {
            this.onEndOfText();
        }
        return true;
    } else {
        return false;
    }
};

/* 当文本结束 */
Window_Message.prototype.onEndOfText = function() {
    if (!this.startInput()) {
        if (!this._pauseSkip) {
            this.startPause();
        } else {
            this.terminateMessage();
        }
    }
    this._textState = null;
};

/* 开始输入 */
Window_Message.prototype.startInput = function() {
    if ($gameMessage.isChoice()) {
        this._choiceWindow.start();
        return true;
    } else if ($gameMessage.isNumberInput()) {
        this._numberWindow.start();
        return true;
    } else if ($gameMessage.isItemChoice()) {
        this._itemWindow.start();
        return true;
    } else {
        return false;
    }
};

/* 是否触发 */
Window_Message.prototype.isTriggered = function() {
    return (Input.isRepeated('ok') || Input.isRepeated('cancel') ||
            TouchInput.isRepeated());
};

/* 是否继续 */
Window_Message.prototype.doesContinue = function() {
    return ($gameMessage.hasText() &amp;&amp; !$gameMessage.scrollMode() &amp;&amp;
            !this.areSettingsChanged());
};

/* 是否设置改变 */
Window_Message.prototype.areSettingsChanged = function() {
    return (this._background !== $gameMessage.background() ||
            this._positionType !== $gameMessage.positionType());
};

/* 更新显示快速 */
Window_Message.prototype.updateShowFast = function() {
    if (this.isTriggered()) {
        this._showFast = true;
    }
};

/* 新页 */
Window_Message.prototype.newPage = function(textState) {
    this.contents.clear();
    this.resetFontSettings();
    this.clearFlags();
    this.loadMessageFace();
    textState.x = this.newLineX();
    textState.y = 0;
    textState.left = this.newLineX();
    textState.height = this.calcTextHeight(textState, false);
};

/* 加载信息脸图 */
Window_Message.prototype.loadMessageFace = function() {
    this._faceBitmap = ImageManager.reserveFace($gameMessage.faceName(), 0, this._imageReservationId);
};

/* 绘制信息脸图 */
Window_Message.prototype.drawMessageFace = function() {
    this.drawFace($gameMessage.faceName(), $gameMessage.faceIndex(), 0, 0);
    ImageManager.releaseReservation(this._imageReservationId);
};

/* 新行 X 坐标 */
Window_Message.prototype.newLineX = function() {
    return $gameMessage.faceName() === '' ? 0 : 168;
};

/* 处理新行 */
Window_Message.prototype.processNewLine = function(textState) {
    this._lineShowFast = false;
    Window_Base.prototype.processNewLine.call(this, textState);
    if (this.needsNewPage(textState)) {
        this.startPause();
    }
};

/* 处理新页 */
Window_Message.prototype.processNewPage = function(textState) {
    Window_Base.prototype.processNewPage.call(this, textState);
    if (textState.text[textState.index] === '\n') {
        textState.index;
    }
    textState.y = this.contents.height;
    this.startPause();
};

/* 是否文本结束 */
Window_Message.prototype.isEndOfText = function(textState) {
    return textState.index &gt;= textState.text.length;
};

/* 是否需要新页 */
Window_Message.prototype.needsNewPage = function(textState) {
    return (!this.isEndOfText(textState) &amp;&amp;
            textState.y + textState.height &gt; this.contents.height);
};

/* 处理转义字符 */
Window_Message.prototype.processEscapeCharacter = function(code, textState) {
    switch (code) {
    case '$':
        this._goldWindow.open();
        break;
    case '.':
        this.startWait(15);
        break;
    case '|':
        this.startWait(60);
        break;
    case '!':
        this.startPause();
        break;
    case '&gt;':
        this._lineShowFast = true;
        break;
    case '&lt;':
        this._lineShowFast = false;
        break;
    case '^':
        this._pauseSkip = true;
        break;
    default:
        Window_Base.prototype.processEscapeCharacter.call(this, code, textState);
        break;
    }
};

/* 开始等待 */
Window_Message.prototype.startWait = function(count) {
    this._waitCount = count;
};

/* 开始暂停 */
Window_Message.prototype.startPause = function() {
    this.startWait(10);
    this.pause = true;
};

//-----------------------------------------------------------------------------
// 窗口_滚动文本 
// Window_ScrollText
//
// 显示滚动文本的窗口。没有边框显示，但为了方便起见，将其作为窗口处理。 
// The window for displaying scrolling text. No frame is displayed, but it
// is handled as a window for convenience.

function Window_ScrollText() {
    this.initialize.apply(this, arguments);
}

Window_ScrollText.prototype = Object.create(Window_Base.prototype);
Window_ScrollText.prototype.constructor = Window_ScrollText;

/* 初始化 */
Window_ScrollText.prototype.initialize = function() {
    var width = Graphics.boxWidth;
    var height = Graphics.boxHeight;
    Window_Base.prototype.initialize.call(this, 0, 0, width, height);
    this.opacity = 0;
    this.hide();
    this._text = '';
    this._allTextHeight = 0;
};

/* 更新 */
Window_ScrollText.prototype.update = function() {
    Window_Base.prototype.update.call(this);
    if ($gameMessage.scrollMode()) {
        if (this._text) {
            this.updateMessage();
        }
        if (!this._text &amp;&amp; $gameMessage.hasText()) {
            this.startMessage();
        }
    }
};

/* 开始信息 */
Window_ScrollText.prototype.startMessage = function() {
    this._text = $gameMessage.allText();
    this.refresh();
    this.show();
};

/* 刷新 */
Window_ScrollText.prototype.refresh = function() {
    var textState = { index: 0 };
    textState.text = this.convertEscapeCharacters(this._text);
    this.resetFontSettings();
    this._allTextHeight = this.calcTextHeight(textState, true);
    this.createContents();
    this.origin.y = -this.height;
    this.drawTextEx(this._text, this.textPadding(), 1);
};

/* 内容高度 */
Window_ScrollText.prototype.contentsHeight = function() {
    return Math.max(this._allTextHeight, 1);
};

/* 更新信息 */
Window_ScrollText.prototype.updateMessage = function() {
    this.origin.y += this.scrollSpeed();
    if (this.origin.y &gt;= this.contents.height) {
        this.terminateMessage();
    }
};

/* 滚动速度 */
Window_ScrollText.prototype.scrollSpeed = function() {
    var speed = $gameMessage.scrollSpeed() / 2;
    if (this.isFastForward()) {
        speed *= this.fastForwardRate();
    }
    return speed;
};

/* 是否快进 */
Window_ScrollText.prototype.isFastForward = function() {
    if ($gameMessage.scrollNoFast()) {
        return false;
    } else {
        return (Input.isPressed('ok') || Input.isPressed('shift') ||
                TouchInput.isPressed());
    }
};

/* 快进倍率 */
Window_ScrollText.prototype.fastForwardRate = function() {
    return 3;
};

/* 结束信息 */
Window_ScrollText.prototype.terminateMessage = function() {
    this._text = null;
    $gameMessage.clear();
    this.hide();
};

//-----------------------------------------------------------------------------
// 窗口_地图名字 
// Window_MapName
//
// 在地图画面上的显示地图名字的窗口。 
// The window for displaying the map name on the map screen.

function Window_MapName() {
    this.initialize.apply(this, arguments);
}

Window_MapName.prototype = Object.create(Window_Base.prototype);
Window_MapName.prototype.constructor = Window_MapName;

/* 初始化 */
Window_MapName.prototype.initialize = function() {
    var wight = this.windowWidth();
    var height = this.windowHeight();
    Window_Base.prototype.initialize.call(this, 0, 0, wight, height);
    this.opacity = 0;
    this.contentsOpacity = 0;
    this._showCount = 0;
    this.refresh();
};

/* 窗口宽度 */
Window_MapName.prototype.windowWidth = function() {
    return 360;
};

/* 窗口高度 */
Window_MapName.prototype.windowHeight = function() {
    return this.fittingHeight(1);
};

/* 更新 */
Window_MapName.prototype.update = function() {
    Window_Base.prototype.update.call(this);
    if (this._showCount &gt; 0 &amp;&amp; $gameMap.isNameDisplayEnabled()) {
        this.updateFadeIn();
        this._showCount--;
    } else {
        this.updateFadeOut();
    }
};

/* 更新淡入 */
Window_MapName.prototype.updateFadeIn = function() {
    this.contentsOpacity += 16;
};

/* 更新淡出 */
Window_MapName.prototype.updateFadeOut = function() {
    this.contentsOpacity -= 16;
};

/* 打开 */
Window_MapName.prototype.open = function() {
    this.refresh();
    this._showCount = 150;
};

/* 关闭 */
Window_MapName.prototype.close = function() {
    this._showCount = 0;
};

/* 刷新 */
Window_MapName.prototype.refresh = function() {
    this.contents.clear();
    if ($gameMap.displayName()) {
        var width = this.contentsWidth();
        this.drawBackground(0, 0, width, this.lineHeight());
        this.drawText($gameMap.displayName(), 0, 0, width, 'center');
    }
};

/* 绘制背景 */
Window_MapName.prototype.drawBackground = function(x, y, width, height) {
    var color1 = this.dimColor1();
    var color2 = this.dimColor2();
    this.contents.gradientFillRect(x, y, width / 2, height, color2, color1);
    this.contents.gradientFillRect(x + width / 2, y, width / 2, height, color1, color2);
};

//-----------------------------------------------------------------------------
// 窗口_战斗日志 
// Window_BattleLog
//
// 显示战斗过程的窗口。没有边框显示，但为了方便起见，将其作为窗口处理。 
// The window for displaying battle progress. No frame is displayed, but it is
// handled as a window for convenience.

function Window_BattleLog() {
    this.initialize.apply(this, arguments);
}

Window_BattleLog.prototype = Object.create(Window_Selectable.prototype);
Window_BattleLog.prototype.constructor = Window_BattleLog;

/* 初始化 */
Window_BattleLog.prototype.initialize = function() {
    var width = this.windowWidth();
    var height = this.windowHeight();
    Window_Selectable.prototype.initialize.call(this, 0, 0, width, height);
    this.opacity = 0;
    this._lines = [];
    this._methods = [];
    this._waitCount = 0;
    this._waitMode = '';
    this._baseLineStack = [];
    this._spriteset = null;
    this.createBackBitmap();
    this.createBackSprite();
    this.refresh();
};

/* 设置精灵组 */
Window_BattleLog.prototype.setSpriteset = function(spriteset) {
    this._spriteset = spriteset;
};

/* 窗口宽度 */
Window_BattleLog.prototype.windowWidth = function() {
    return Graphics.boxWidth;
};

/* 窗口高度 */
Window_BattleLog.prototype.windowHeight = function() {
    return this.fittingHeight(this.maxLines());
};

/* 最大行数 */
Window_BattleLog.prototype.maxLines = function() {
    return 10;
};

/* 创建背景位图 */
Window_BattleLog.prototype.createBackBitmap = function() {
    this._backBitmap = new Bitmap(this.width, this.height);
};

/* 创建背景精灵 */
Window_BattleLog.prototype.createBackSprite = function() {
    this._backSprite = new Sprite();
    this._backSprite.bitmap = this._backBitmap;
    this._backSprite.y = this.y;
    this.addChildToBack(this._backSprite);
};

/* 行数 */
Window_BattleLog.prototype.numLines = function() {
    return this._lines.length;
};

/* 信息速度 */
Window_BattleLog.prototype.messageSpeed = function() {
    return 16;
};

/* 是否繁忙 */
Window_BattleLog.prototype.isBusy = function() {
    return this._waitCount &gt; 0 || this._waitMode || this._methods.length &gt; 0;
};

/* 更新 */
Window_BattleLog.prototype.update = function() {
    if (!this.updateWait()) {
        this.callNextMethod();
    }
};

/* 更新等待 */
Window_BattleLog.prototype.updateWait = function() {
    return this.updateWaitCount() || this.updateWaitMode();
};

/* 更新等待计数 */
Window_BattleLog.prototype.updateWaitCount = function() {
    if (this._waitCount &gt; 0) {
        this._waitCount -= this.isFastForward() ? 3 : 1;
        if (this._waitCount &lt; 0) {
            this._waitCount = 0;
        }
        return true;
    }
    return false;
};

/* 更新等待模式 */
Window_BattleLog.prototype.updateWaitMode = function() {
    var waiting = false;
    switch (this._waitMode) {
    case 'effect':
        waiting = this._spriteset.isEffecting();
        break;
    case 'movement':
        waiting = this._spriteset.isAnyoneMoving();
        break;
    }
    if (!waiting) {
        this._waitMode = '';
    }
    return waiting;
};

/* 设置等待模式 */
Window_BattleLog.prototype.setWaitMode = function(waitMode) {
    this._waitMode = waitMode;
};

/* 呼叫下一个方法 */
Window_BattleLog.prototype.callNextMethod = function() {
    if (this._methods.length &gt; 0) {
        var method = this._methods.shift();
        if (method.name &amp;&amp; this[method.name]) {
            this[method.name].apply(this, method.params);
        } else {
            throw new Error('Method not found: ' + method.name);
        }
    }
};

/* 是否快进 */
Window_BattleLog.prototype.isFastForward = function() {
    return (Input.isLongPressed('ok') || Input.isPressed('shift') ||
            TouchInput.isLongPressed());
};

/* 入栈 */
Window_BattleLog.prototype.push = function(methodName) {
    var methodArgs = Array.prototype.slice.call(arguments, 1);
    this._methods.push({ name: methodName, params: methodArgs });
};

/* 清空 */
Window_BattleLog.prototype.clear = function() {
    this._lines = [];
    this._baseLineStack = [];
    this.refresh();
};

/* 等待 */
Window_BattleLog.prototype.wait = function() {
    this._waitCount = this.messageSpeed();
};

/* 等待效果 */
Window_BattleLog.prototype.waitForEffect = function() {
    this.setWaitMode('effect');
};

/* 等待移动 */
Window_BattleLog.prototype.waitForMovement = function() {
    this.setWaitMode('movement');
};

/* 增加文本 */
Window_BattleLog.prototype.addText = function(text) {
    this._lines.push(text);
    this.refresh();
    this.wait();
};

/* 增加基础行 */
Window_BattleLog.prototype.pushBaseLine = function() {
    this._baseLineStack.push(this._lines.length);
};

/* 移除基础行 */
Window_BattleLog.prototype.popBaseLine = function() {
    var baseLine = this._baseLineStack.pop();
    while (this._lines.length &gt; baseLine) {
        this._lines.pop();
    }
};

/* 等待新行 */
Window_BattleLog.prototype.waitForNewLine = function() {
    var baseLine = 0;
    if (this._baseLineStack.length &gt; 0) {
        baseLine = this._baseLineStack[this._baseLineStack.length - 1];
    }
    if (this._lines.length &gt; baseLine) {
        this.wait();
    }
};

/* 弹出伤害 */
Window_BattleLog.prototype.popupDamage = function(target) {
    target.startDamagePopup();
};

/* 表现行动开始 */
Window_BattleLog.prototype.performActionStart = function(subject, action) {
    subject.performActionStart(action);
};

/* 表现行动 */
Window_BattleLog.prototype.performAction = function(subject, action) {
    subject.performAction(action);
};

/* 表现行动结束 */
Window_BattleLog.prototype.performActionEnd = function(subject) {
    subject.performActionEnd();
};

/* 表现伤害 */
Window_BattleLog.prototype.performDamage = function(target) {
    target.performDamage();
};

/* 表现未命中 */
Window_BattleLog.prototype.performMiss = function(target) {
    target.performMiss();
};

/* 表现行动结束 */
Window_BattleLog.prototype.performRecovery = function(target) {
    target.performRecovery();
};

/* 表现闪避 */
Window_BattleLog.prototype.performEvasion = function(target) {
    target.performEvasion();
};

/* 表现魔法闪避 */
Window_BattleLog.prototype.performMagicEvasion = function(target) {
    target.performMagicEvasion();
};

/* 表现反击 */
Window_BattleLog.prototype.performCounter = function(target) {
    target.performCounter();
};

/* 表现魔法反射 */
Window_BattleLog.prototype.performReflection = function(target) {
    target.performReflection();
};

/* 表现掩护 */
Window_BattleLog.prototype.performSubstitute = function(substitute, target) {
    substitute.performSubstitute(target);
};

/* 表现倒下（死亡后的消失效果） */
Window_BattleLog.prototype.performCollapse = function(target) {
    target.performCollapse();
};

/* 显示动画 */
Window_BattleLog.prototype.showAnimation = function(subject, targets, animationId) {
    if (animationId &lt; 0) {
        this.showAttackAnimation(subject, targets);
    } else {
        this.showNormalAnimation(targets, animationId);
    }
};

/* 显示攻击动画 */
Window_BattleLog.prototype.showAttackAnimation = function(subject, targets) {
    if (subject.isActor()) {
        this.showActorAttackAnimation(subject, targets);
    } else {
        this.showEnemyAttackAnimation(subject, targets);
    }
};

/* 显示角色攻击动画 */
Window_BattleLog.prototype.showActorAttackAnimation = function(subject, targets) {
    this.showNormalAnimation(targets, subject.attackAnimationId1(), false);
    this.showNormalAnimation(targets, subject.attackAnimationId2(), true);
};

/* 显示敌人攻击动画 */
Window_BattleLog.prototype.showEnemyAttackAnimation = function(subject, targets) {
    SoundManager.playEnemyAttack();
};

/* 显示普通动画 */
Window_BattleLog.prototype.showNormalAnimation = function(targets, animationId, mirror) {
    var animation = $dataAnimations[animationId];
    if (animation) {
        var delay = this.animationBaseDelay();
        var nextDelay = this.animationNextDelay();
        targets.forEach(function(target) {
            target.startAnimation(animationId, mirror, delay);
            delay += nextDelay;
        });
    }
};

/* 动画基础延迟 */
Window_BattleLog.prototype.animationBaseDelay = function() {
    return 8;
};

/* 动画下一个延迟 */
Window_BattleLog.prototype.animationNextDelay = function() {
    return 12;
};

/* 刷新 */
Window_BattleLog.prototype.refresh = function() {
    this.drawBackground();
    this.contents.clear();
    for (var i = 0; i &lt; this._lines.length; i) {
        this.drawLineText(i);
    }
};

/* 绘制背景 */
Window_BattleLog.prototype.drawBackground = function() {
    var rect = this.backRect();
    var color = this.backColor();
    this._backBitmap.clear();
    this._backBitmap.paintOpacity = this.backPaintOpacity();
    this._backBitmap.fillRect(rect.x, rect.y, rect.width, rect.height, color);
    this._backBitmap.paintOpacity = 255;
};

/* 背景矩形区域 */
Window_BattleLog.prototype.backRect = function() {
    return {
        x: 0,
        y: this.padding,
        width: this.width,
        height: this.numLines() * this.lineHeight()
    };
};

/* 背景颜色 */
Window_BattleLog.prototype.backColor = function() {
    return '#000000';
};

/* 背景绘画不透明度 */
Window_BattleLog.prototype.backPaintOpacity = function() {
    return 64;
};

/* 绘制行文本 */
Window_BattleLog.prototype.drawLineText = function(index) {
    var rect = this.itemRectForText(index);
    this.contents.clearRect(rect.x, rect.y, rect.width, rect.height);
    this.drawTextEx(this._lines[index], rect.x, rect.y, rect.width);
};

/* 开始回合 */
Window_BattleLog.prototype.startTurn = function() {
    this.push('wait');
};

/* 开始行动 */
Window_BattleLog.prototype.startAction = function(subject, action, targets) {
    var item = action.item();
    this.push('performActionStart', subject, action);
    this.push('waitForMovement');
    this.push('performAction', subject, action);
    this.push('showAnimation', subject, targets.clone(), item.animationId);
    this.displayAction(subject, item);
};

/* 结束行动 */
Window_BattleLog.prototype.endAction = function(subject) {
    this.push('waitForNewLine');
    this.push('clear');
    this.push('performActionEnd', subject);
};

/* 显示当前状态 */
Window_BattleLog.prototype.displayCurrentState = function(subject) {
    var stateText = subject.mostImportantStateText();
    if (stateText) {
        this.push('addText', subject.name() + stateText);
        this.push('wait');
        this.push('clear');
    }
};

/* 显示恢复 */
Window_BattleLog.prototype.displayRegeneration = function(subject) {
    this.push('popupDamage', subject);
};

/* 显示行动 */
Window_BattleLog.prototype.displayAction = function(subject, item) {
    var numMethods = this._methods.length;
    if (DataManager.isSkill(item)) {
        if (item.message1) {
            this.push('addText', subject.name() + item.message1.format(item.name));
        }
        if (item.message2) {
            this.push('addText', item.message2.format(item.name));
        }
    } else {
        this.push('addText', TextManager.useItem.format(subject.name(), item.name));
    }
    if (this._methods.length === numMethods) {
        this.push('wait');
    }
};

/* 显示反击 */
Window_BattleLog.prototype.displayCounter = function(target) {
    this.push('performCounter', target);
    this.push('addText', TextManager.counterAttack.format(target.name()));
};

/* 显示反射 */
Window_BattleLog.prototype.displayReflection = function(target) {
    this.push('performReflection', target);
    this.push('addText', TextManager.magicReflection.format(target.name()));
};

/* 显示掩护 */
Window_BattleLog.prototype.displaySubstitute = function(substitute, target) {
    var substName = substitute.name();
    this.push('performSubstitute', substitute, target);
    this.push('addText', TextManager.substitute.format(substName, target.name()));
};

/* 显示行动结果 */
Window_BattleLog.prototype.displayActionResults = function(subject, target) {
    if (target.result().used) {
        this.push('pushBaseLine');
        this.displayCritical(target);
        this.push('popupDamage', target);
        this.push('popupDamage', subject);
        this.displayDamage(target);
        this.displayAffectedStatus(target);
        this.displayFailure(target);
        this.push('waitForNewLine');
        this.push('popBaseLine');
    }
};

/* 显示失败 */
Window_BattleLog.prototype.displayFailure = function(target) {
    if (target.result().isHit() &amp;&amp; !target.result().success) {
        this.push('addText', TextManager.actionFailure.format(target.name()));
    }
};

/* 显示暴击 */
Window_BattleLog.prototype.displayCritical = function(target) {
    if (target.result().critical) {
        if (target.isActor()) {
            this.push('addText', TextManager.criticalToActor);
        } else {
            this.push('addText', TextManager.criticalToEnemy);
        }
    }
};

/* 显示伤害 */
Window_BattleLog.prototype.displayDamage = function(target) {
    if (target.result().missed) {
        this.displayMiss(target);
    } else if (target.result().evaded) {
        this.displayEvasion(target);
    } else {
        this.displayHpDamage(target);
        this.displayMpDamage(target);
        this.displayTpDamage(target);
    }
};

/* 显示未命中 */
Window_BattleLog.prototype.displayMiss = function(target) {
    var fmt;
    if (target.result().physical) {
        fmt = target.isActor() ? TextManager.actorNoHit : TextManager.enemyNoHit;
        this.push('performMiss', target);
    } else {
        fmt = TextManager.actionFailure;
    }
    this.push('addText', fmt.format(target.name()));
};

/* 显示闪避 */
Window_BattleLog.prototype.displayEvasion = function(target) {
    var fmt;
    if (target.result().physical) {
        fmt = TextManager.evasion;
        this.push('performEvasion', target);
    } else {
        fmt = TextManager.magicEvasion;
        this.push('performMagicEvasion', target);
    }
    this.push('addText', fmt.format(target.name()));
};

/* 显示 HP 伤害 */
Window_BattleLog.prototype.displayHpDamage = function(target) {
    if (target.result().hpAffected) {
        if (target.result().hpDamage &gt; 0 &amp;&amp; !target.result().drain) {
            this.push('performDamage', target);
        }
        if (target.result().hpDamage &lt; 0) {
            this.push('performRecovery', target);
        }
        this.push('addText', this.makeHpDamageText(target));
    }
};

/* 显示 MP 伤害 */
Window_BattleLog.prototype.displayMpDamage = function(target) {
    if (target.isAlive() &amp;&amp; target.result().mpDamage !== 0) {
        if (target.result().mpDamage &lt; 0) {
            this.push('performRecovery', target);
        }
        this.push('addText', this.makeMpDamageText(target));
    }
};

/* 显示 TP 伤害 */
Window_BattleLog.prototype.displayTpDamage = function(target) {
    if (target.isAlive() &amp;&amp; target.result().tpDamage !== 0) {
        if (target.result().tpDamage &lt; 0) {
            this.push('performRecovery', target);
        }
        this.push('addText', this.makeTpDamageText(target));
    }
};

/* 显示受影响的状态 */
Window_BattleLog.prototype.displayAffectedStatus = function(target) {
    if (target.result().isStatusAffected()) {
        this.push('pushBaseLine');
        this.displayChangedStates(target);
        this.displayChangedBuffs(target);
        this.push('waitForNewLine');
        this.push('popBaseLine');
    }
};

/* 自动显示受影响的状态 */
Window_BattleLog.prototype.displayAutoAffectedStatus = function(target) {
    if (target.result().isStatusAffected()) {
        this.displayAffectedStatus(target, null);
        this.push('clear');
    }
};

/* 显示改变的状态 */
Window_BattleLog.prototype.displayChangedStates = function(target) {
    this.displayAddedStates(target);
    this.displayRemovedStates(target);
};

/* 显示附加的状态 */
Window_BattleLog.prototype.displayAddedStates = function(target) {
    target.result().addedStateObjects().forEach(function(state) {
        var stateMsg = target.isActor() ? state.message1 : state.message2;
        if (state.id === target.deathStateId()) {
            this.push('performCollapse', target);
        }
        if (stateMsg) {
            this.push('popBaseLine');
            this.push('pushBaseLine');
            this.push('addText', target.name() + stateMsg);
            this.push('waitForEffect');
        }
    }, this);
};

/* 显示解除的状态 */
Window_BattleLog.prototype.displayRemovedStates = function(target) {
    target.result().removedStateObjects().forEach(function(state) {
        if (state.message4) {
            this.push('popBaseLine');
            this.push('pushBaseLine');
            this.push('addText', target.name() + state.message4);
        }
    }, this);
};

/* 显示改变的强化/弱化效果 */
Window_BattleLog.prototype.displayChangedBuffs = function(target) {
    var result = target.result();
    this.displayBuffs(target, result.addedBuffs, TextManager.buffAdd);
    this.displayBuffs(target, result.addedDebuffs, TextManager.debuffAdd);
    this.displayBuffs(target, result.removedBuffs, TextManager.buffRemove);
};

/* 显示强化/弱化效果 */
Window_BattleLog.prototype.displayBuffs = function(target, buffs, fmt) {
    buffs.forEach(function(paramId) {
        this.push('popBaseLine');
        this.push('pushBaseLine');
        this.push('addText', fmt.format(target.name(), TextManager.param(paramId)));
    }, this);
};

/* 制作 HP 伤害文本 */
Window_BattleLog.prototype.makeHpDamageText = function(target) {
    var result = target.result();
    var damage = result.hpDamage;
    var isActor = target.isActor();
    var fmt;
    if (damage &gt; 0 &amp;&amp; result.drain) {
        fmt = isActor ? TextManager.actorDrain : TextManager.enemyDrain;
        return fmt.format(target.name(), TextManager.hp, damage);
    } else if (damage &gt; 0) {
        fmt = isActor ? TextManager.actorDamage : TextManager.enemyDamage;
        return fmt.format(target.name(), damage);
    } else if (damage &lt; 0) {
        fmt = isActor ? TextManager.actorRecovery : TextManager.enemyRecovery;
        return fmt.format(target.name(), TextManager.hp, -damage);
    } else {
        fmt = isActor ? TextManager.actorNoDamage : TextManager.enemyNoDamage;
        return fmt.format(target.name());
    }
};

/* 制作 MP 伤害文本 */
Window_BattleLog.prototype.makeMpDamageText = function(target) {
    var result = target.result();
    var damage = result.mpDamage;
    var isActor = target.isActor();
    var fmt;
    if (damage &gt; 0 &amp;&amp; result.drain) {
        fmt = isActor ? TextManager.actorDrain : TextManager.enemyDrain;
        return fmt.format(target.name(), TextManager.mp, damage);
    } else if (damage &gt; 0) {
        fmt = isActor ? TextManager.actorLoss : TextManager.enemyLoss;
        return fmt.format(target.name(), TextManager.mp, damage);
    } else if (damage &lt; 0) {
        fmt = isActor ? TextManager.actorRecovery : TextManager.enemyRecovery;
        return fmt.format(target.name(), TextManager.mp, -damage);
    } else {
        return '';
    }
};

/* 制作 TP 伤害文本 */
Window_BattleLog.prototype.makeTpDamageText = function(target) {
    var result = target.result();
    var damage = result.tpDamage;
    var isActor = target.isActor();
    var fmt;
    if (damage &gt; 0) {
        fmt = isActor ? TextManager.actorLoss : TextManager.enemyLoss;
        return fmt.format(target.name(), TextManager.tp, damage);
    } else if (damage &lt; 0) {
        fmt = isActor ? TextManager.actorGain : TextManager.enemyGain;
        return fmt.format(target.name(), TextManager.tp, -damage);
    } else {
        return '';
    }
};

//-----------------------------------------------------------------------------
// 窗口_队伍指令 
// Window_PartyCommand
//
// 在战斗画面上的选择是战斗还是逃跑的窗口。 
// The window for selecting whether to fight or escape on the battle screen.

function Window_PartyCommand() {
    this.initialize.apply(this, arguments);
}

Window_PartyCommand.prototype = Object.create(Window_Command.prototype);
Window_PartyCommand.prototype.constructor = Window_PartyCommand;

/* 初始化 */
Window_PartyCommand.prototype.initialize = function() {
    var y = Graphics.boxHeight - this.windowHeight();
    Window_Command.prototype.initialize.call(this, 0, y);
    this.openness = 0;
    this.deactivate();
};

/* 窗口宽度 */
Window_PartyCommand.prototype.windowWidth = function() {
    return 192;
};

/* 可见的行数 */
Window_PartyCommand.prototype.numVisibleRows = function() {
    return 4;
};

/* 制作指令列表 */
Window_PartyCommand.prototype.makeCommandList = function() {
    this.addCommand(TextManager.fight,  'fight');
    this.addCommand(TextManager.escape, 'escape', BattleManager.canEscape());
};

/* 设置 */
Window_PartyCommand.prototype.setup = function() {
    this.clearCommandList();
    this.makeCommandList();
    this.refresh();
    this.select(0);
    this.activate();
    this.open();
};

//-----------------------------------------------------------------------------
// 窗口_角色指令 
// Window_ActorCommand
//
// 在战斗画面上的选择角色行动的窗口。 
// The window for selecting an actor's action on the battle screen.

function Window_ActorCommand() {
    this.initialize.apply(this, arguments);
}

Window_ActorCommand.prototype = Object.create(Window_Command.prototype);
Window_ActorCommand.prototype.constructor = Window_ActorCommand;

/* 初始化 */
Window_ActorCommand.prototype.initialize = function() {
    var y = Graphics.boxHeight - this.windowHeight();
    Window_Command.prototype.initialize.call(this, 0, y);
    this.openness = 0;
    this.deactivate();
    this._actor = null;
};

/* 窗口宽度 */
Window_ActorCommand.prototype.windowWidth = function() {
    return 192;
};

/* 可见的行数 */
Window_ActorCommand.prototype.numVisibleRows = function() {
    return 4;
};

/* 制作指令列表 */
Window_ActorCommand.prototype.makeCommandList = function() {
    if (this._actor) {
        this.addAttackCommand();
        this.addSkillCommands();
        this.addGuardCommand();
        this.addItemCommand();
    }
};

/* 增加攻击指令 */
Window_ActorCommand.prototype.addAttackCommand = function() {
    this.addCommand(TextManager.attack, 'attack', this._actor.canAttack());
};

/* 增加技能指令 */
Window_ActorCommand.prototype.addSkillCommands = function() {
    var skillTypes = this._actor.addedSkillTypes();
    skillTypes.sort(function(a, b) {
        return a - b;
    });
    skillTypes.forEach(function(stypeId) {
        var name = $dataSystem.skillTypes[stypeId];
        this.addCommand(name, 'skill', true, stypeId);
    }, this);
};

/* 增加防御指令 */
Window_ActorCommand.prototype.addGuardCommand = function() {
    this.addCommand(TextManager.guard, 'guard', this._actor.canGuard());
};

/* 增加物品指令 */
Window_ActorCommand.prototype.addItemCommand = function() {
    this.addCommand(TextManager.item, 'item');
};

/* 设置 */
Window_ActorCommand.prototype.setup = function(actor) {
    this._actor = actor;
    this.clearCommandList();
    this.makeCommandList();
    this.refresh();
    this.selectLast();
    this.activate();
    this.open();
};

/* 处理确定 */
Window_ActorCommand.prototype.processOk = function() {
    if (this._actor) {
        if (ConfigManager.commandRemember) {
            this._actor.setLastCommandSymbol(this.currentSymbol());
        } else {
            this._actor.setLastCommandSymbol('');
        }
    }
    Window_Command.prototype.processOk.call(this);
};

/* 选择上一个 */
Window_ActorCommand.prototype.selectLast = function() {
    this.select(0);
    if (this._actor &amp;&amp; ConfigManager.commandRemember) {
        var symbol = this._actor.lastCommandSymbol();
        this.selectSymbol(symbol);
        if (symbol === 'skill') {
            var skill = this._actor.lastBattleSkill();
            if (skill) {
                this.selectExt(skill.stypeId);
            }
        }
    }
};

//-----------------------------------------------------------------------------
// 窗口_战斗状态 
// Window_BattleStatus
//
// 在战斗画面上的显示队伍成员状态的窗口。 
// The window for displaying the status of party members on the battle screen.

function Window_BattleStatus() {
    this.initialize.apply(this, arguments);
}

Window_BattleStatus.prototype = Object.create(Window_Selectable.prototype);
Window_BattleStatus.prototype.constructor = Window_BattleStatus;

/* 初始化 */
Window_BattleStatus.prototype.initialize = function() {
    var width = this.windowWidth();
    var height = this.windowHeight();
    var x = Graphics.boxWidth - width;
    var y = Graphics.boxHeight - height;
    Window_Selectable.prototype.initialize.call(this, x, y, width, height);
    this.refresh();
    this.openness = 0;
};

/* 窗口宽度 */
Window_BattleStatus.prototype.windowWidth = function() {
    return Graphics.boxWidth - 192;
};

/* 窗口高度 */
Window_BattleStatus.prototype.windowHeight = function() {
    return this.fittingHeight(this.numVisibleRows());
};

/* 可见的行数 */
Window_BattleStatus.prototype.numVisibleRows = function() {
    return 4;
};

/* 最大项目数 */
Window_BattleStatus.prototype.maxItems = function() {
    return $gameParty.battleMembers().length;
};

/* 刷新 */
Window_BattleStatus.prototype.refresh = function() {
    this.contents.clear();
    this.drawAllItems();
};

/* 绘制项目 */
Window_BattleStatus.prototype.drawItem = function(index) {
    var actor = $gameParty.battleMembers()[index];
    this.drawBasicArea(this.basicAreaRect(index), actor);
    this.drawGaugeArea(this.gaugeAreaRect(index), actor);
};

/* 基础区域矩形 */
Window_BattleStatus.prototype.basicAreaRect = function(index) {
    var rect = this.itemRectForText(index);
    rect.width -= this.gaugeAreaWidth() + 15;
    return rect;
};

/* 计量区域矩形 */
Window_BattleStatus.prototype.gaugeAreaRect = function(index) {
    var rect = this.itemRectForText(index);
    rect.x += rect.width - this.gaugeAreaWidth();
    rect.width = this.gaugeAreaWidth();
    return rect;
};

/* 计量区域宽 */
Window_BattleStatus.prototype.gaugeAreaWidth = function() {
    return 330;
};

/* 绘制基础区域 */
Window_BattleStatus.prototype.drawBasicArea = function(rect, actor) {
    this.drawActorName(actor, rect.x + 0, rect.y, 150);
    this.drawActorIcons(actor, rect.x + 156, rect.y, rect.width - 156);
};

/* 绘制计量区域 */
Window_BattleStatus.prototype.drawGaugeArea = function(rect, actor) {
    if ($dataSystem.optDisplayTp) {
        this.drawGaugeAreaWithTp(rect, actor);
    } else {
        this.drawGaugeAreaWithoutTp(rect, actor);
    }
};

/* 绘制有 TP 的计量区域 */
Window_BattleStatus.prototype.drawGaugeAreaWithTp = function(rect, actor) {
    this.drawActorHp(actor, rect.x + 0, rect.y, 108);
    this.drawActorMp(actor, rect.x + 123, rect.y, 96);
    this.drawActorTp(actor, rect.x + 234, rect.y, 96);
};

/* 绘制没有 TP 的计量区域 */
Window_BattleStatus.prototype.drawGaugeAreaWithoutTp = function(rect, actor) {
    this.drawActorHp(actor, rect.x + 0, rect.y, 201);
    this.drawActorMp(actor, rect.x + 216,  rect.y, 114);
};

//-----------------------------------------------------------------------------
// 窗口_战斗角色 
// Window_BattleActor
//
// 在战斗画面上的选择目标角色的窗口。 
// The window for selecting a target actor on the battle screen.

function Window_BattleActor() {
    this.initialize.apply(this, arguments);
}

Window_BattleActor.prototype = Object.create(Window_BattleStatus.prototype);
Window_BattleActor.prototype.constructor = Window_BattleActor;

/* 初始化 */
Window_BattleActor.prototype.initialize = function(x, y) {
    Window_BattleStatus.prototype.initialize.call(this);
    this.x = x;
    this.y = y;
    this.openness = 255;
    this.hide();
};

/* 显示 */
Window_BattleActor.prototype.show = function() {
    this.select(0);
    Window_BattleStatus.prototype.show.call(this);
};

/* 隐藏 */
Window_BattleActor.prototype.hide = function() {
    Window_BattleStatus.prototype.hide.call(this);
    $gameParty.select(null);
};

/* 选择 */
Window_BattleActor.prototype.select = function(index) {
    Window_BattleStatus.prototype.select.call(this, index);
    $gameParty.select(this.actor());
};

/* 角色 */
Window_BattleActor.prototype.actor = function() {
    return $gameParty.members()[this.index()];
};

//-----------------------------------------------------------------------------
// 窗口_战斗敌人 
// Window_BattleEnemy
//
// 在战斗画面上的选择目标敌人的窗口。 
// The window for selecting a target enemy on the battle screen.

function Window_BattleEnemy() {
    this.initialize.apply(this, arguments);
}

Window_BattleEnemy.prototype = Object.create(Window_Selectable.prototype);
Window_BattleEnemy.prototype.constructor = Window_BattleEnemy;

/* 初始化 */
Window_BattleEnemy.prototype.initialize = function(x, y) {
    this._enemies = [];
    var width = this.windowWidth();
    var height = this.windowHeight();
    Window_Selectable.prototype.initialize.call(this, x, y, width, height);
    this.refresh();
    this.hide();
};

/* 窗口宽度 */
Window_BattleEnemy.prototype.windowWidth = function() {
    return Graphics.boxWidth - 192;
};

/* 窗口高度 */
Window_BattleEnemy.prototype.windowHeight = function() {
    return this.fittingHeight(this.numVisibleRows());
};

/* 可见的行数 */
Window_BattleEnemy.prototype.numVisibleRows = function() {
    return 4;
};

/* 最大行数 */
Window_BattleEnemy.prototype.maxCols = function() {
    return 2;
};

/* 最大项目数 */
Window_BattleEnemy.prototype.maxItems = function() {
    return this._enemies.length;
};

/* 敌人 */
Window_BattleEnemy.prototype.enemy = function() {
    return this._enemies[this.index()];
};

/* 敌人索引 */
Window_BattleEnemy.prototype.enemyIndex = function() {
    var enemy = this.enemy();
    return enemy ? enemy.index() : -1;
};

/* 绘制项目 */
Window_BattleEnemy.prototype.drawItem = function(index) {
    this.resetTextColor();
    var name = this._enemies[index].name();
    var rect = this.itemRectForText(index);
    this.drawText(name, rect.x, rect.y, rect.width);
};

/* 显示 */
Window_BattleEnemy.prototype.show = function() {
    this.refresh();
    this.select(0);
    Window_Selectable.prototype.show.call(this);
};

/* 隐藏 */
Window_BattleEnemy.prototype.hide = function() {
    Window_Selectable.prototype.hide.call(this);
    $gameTroop.select(null);
};

/* 刷新 */
Window_BattleEnemy.prototype.refresh = function() {
    this._enemies = $gameTroop.aliveMembers();
    Window_Selectable.prototype.refresh.call(this);
};

/* 选择 */
Window_BattleEnemy.prototype.select = function(index) {
    Window_Selectable.prototype.select.call(this, index);
    $gameTroop.select(this.enemy());
};

//-----------------------------------------------------------------------------
// 窗口_战斗技能 
// Window_BattleSkill
//
// 在战斗画面上的选择要使用的技能的窗口。 
// The window for selecting a skill to use on the battle screen.

function Window_BattleSkill() {
    this.initialize.apply(this, arguments);
}

Window_BattleSkill.prototype = Object.create(Window_SkillList.prototype);
Window_BattleSkill.prototype.constructor = Window_BattleSkill;

/* 初始化 */
Window_BattleSkill.prototype.initialize = function(x, y, width, height) {
    Window_SkillList.prototype.initialize.call(this, x, y, width, height);
    this.hide();
};

/* 显示 */
Window_BattleSkill.prototype.show = function() {
    this.selectLast();
    this.showHelpWindow();
    Window_SkillList.prototype.show.call(this);
};

/* 隐藏 */
Window_BattleSkill.prototype.hide = function() {
    this.hideHelpWindow();
    Window_SkillList.prototype.hide.call(this);
};

//-----------------------------------------------------------------------------
// 窗口_战斗物品 
// Window_BattleItem
//
// 在战斗画面上的选择要使用的物品的窗口。 
// The window for selecting an item to use on the battle screen.

function Window_BattleItem() {
    this.initialize.apply(this, arguments);
}

Window_BattleItem.prototype = Object.create(Window_ItemList.prototype);
Window_BattleItem.prototype.constructor = Window_BattleItem;

/* 初始化 */
Window_BattleItem.prototype.initialize = function(x, y, width, height) {
    Window_ItemList.prototype.initialize.call(this, x, y, width, height);
    this.hide();
};

/* 包含 */
Window_BattleItem.prototype.includes = function(item) {
    return $gameParty.canUse(item);
};

/* 显示 */
Window_BattleItem.prototype.show = function() {
    this.selectLast();
    this.showHelpWindow();
    Window_ItemList.prototype.show.call(this);
};

/* 隐藏 */
Window_BattleItem.prototype.hide = function() {
    this.hideHelpWindow();
    Window_ItemList.prototype.hide.call(this);
};

//-----------------------------------------------------------------------------
// 窗口_标题指令 
// Window_TitleCommand
//
// 在标题画面上的选择新游戏/继续的窗口。 
// The window for selecting New Game/Continue on the title screen. 

function Window_TitleCommand() {
    this.initialize.apply(this, arguments);
}

Window_TitleCommand.prototype = Object.create(Window_Command.prototype);
Window_TitleCommand.prototype.constructor = Window_TitleCommand;

/* 初始化 */
Window_TitleCommand.prototype.initialize = function() {
    Window_Command.prototype.initialize.call(this, 0, 0);
    this.updatePlacement();
    this.openness = 0;
    this.selectLast();
};

Window_TitleCommand._lastCommandSymbol = null;  // 上一次选择的指令标识 

/* 初始化指令位置 */
Window_TitleCommand.initCommandPosition = function() {
    this._lastCommandSymbol = null;
};

/* 窗口宽度 */
Window_TitleCommand.prototype.windowWidth = function() {
    return 240;
};

/* 更新位置 */
Window_TitleCommand.prototype.updatePlacement = function() {
    this.x = (Graphics.boxWidth - this.width) / 2;
    this.y = Graphics.boxHeight - this.height - 96;
};

/* 制作指令列表 */
Window_TitleCommand.prototype.makeCommandList = function() {
    this.addCommand(TextManager.newGame,   'newGame');
    this.addCommand(TextManager.continue_, 'continue', this.isContinueEnabled());
    this.addCommand(TextManager.options,   'options');
};

/* 是否继续游戏启用 */
Window_TitleCommand.prototype.isContinueEnabled = function() {
    return DataManager.isAnySavefileExists();
};

/* 处理确定 */
Window_TitleCommand.prototype.processOk = function() {
    Window_TitleCommand._lastCommandSymbol = this.currentSymbol();
    Window_Command.prototype.processOk.call(this);
};

/* 选择上一次 */
Window_TitleCommand.prototype.selectLast = function() {
    if (Window_TitleCommand._lastCommandSymbol) {
        this.selectSymbol(Window_TitleCommand._lastCommandSymbol);
    } else if (this.isContinueEnabled()) {
        this.selectSymbol('continue');
    }
};

//-----------------------------------------------------------------------------
// 窗口_游戏结束 
// Window_GameEnd
//
// 在游戏结束画面上的选择“回到标题”的窗口。 
// The window for selecting "Go to Title" on the game end screen.

function Window_GameEnd() {
    this.initialize.apply(this, arguments);
}

Window_GameEnd.prototype = Object.create(Window_Command.prototype);
Window_GameEnd.prototype.constructor = Window_GameEnd;

/* 初始化 */
Window_GameEnd.prototype.initialize = function() {
    Window_Command.prototype.initialize.call(this, 0, 0);
    this.updatePlacement();
    this.openness = 0;
    this.open();
};

/* 窗口宽 */
Window_GameEnd.prototype.windowWidth = function() {
    return 240;
};

/* 更新位置 */
Window_GameEnd.prototype.updatePlacement = function() {
    this.x = (Graphics.boxWidth - this.width) / 2;
    this.y = (Graphics.boxHeight - this.height) / 2;
};

/* 制作指令列表 */
Window_GameEnd.prototype.makeCommandList = function() {
    this.addCommand(TextManager.toTitle, 'toTitle');
    this.addCommand(TextManager.cancel,  'cancel');
};

//-----------------------------------------------------------------------------
// 窗口_调试范围 
// Window_DebugRange
//
// 在调试画面上的选择一块开关/变量的窗口。 
// The window for selecting a block of switches/variables on the debug screen.

function Window_DebugRange() {
    this.initialize.apply(this, arguments);
}

Window_DebugRange.prototype = Object.create(Window_Selectable.prototype);
Window_DebugRange.prototype.constructor = Window_DebugRange;

Window_DebugRange.lastTopRow = 0;  // 上一个顶部行数 
Window_DebugRange.lastIndex  = 0;  // 上一个索引 

/* 初始化 */
Window_DebugRange.prototype.initialize = function(x, y) {
    this._maxSwitches = Math.ceil(($dataSystem.switches.length - 1) / 10);
    this._maxVariables = Math.ceil(($dataSystem.variables.length - 1) / 10);
    var width = this.windowWidth();
    var height = this.windowHeight();
    Window_Selectable.prototype.initialize.call(this, x, y, width, height);
    this.refresh();
    this.setTopRow(Window_DebugRange.lastTopRow);
    this.select(Window_DebugRange.lastIndex);
    this.activate();
};

/* 窗口宽度 */
Window_DebugRange.prototype.windowWidth = function() {
    return 246;
};

/* 窗口高度 */
Window_DebugRange.prototype.windowHeight = function() {
    return Graphics.boxHeight;
};

/* 最大项目数 */
Window_DebugRange.prototype.maxItems = function() {
    return this._maxSwitches + this._maxVariables;
};

/* 更新 */
Window_DebugRange.prototype.update = function() {
    Window_Selectable.prototype.update.call(this);
    if (this._editWindow) {
        this._editWindow.setMode(this.mode());
        this._editWindow.setTopId(this.topId());
    }
};

/* 模式 */
Window_DebugRange.prototype.mode = function() {
    return this.index() &lt; this._maxSwitches ? 'switch' : 'variable';
};

/* 顶部 ID */
Window_DebugRange.prototype.topId = function() {
    var index = this.index();
    if (index &lt; this._maxSwitches) {
        return index * 10 + 1;
    } else {
        return (index - this._maxSwitches) * 10 + 1;
    }
};

/* 刷新 */
Window_DebugRange.prototype.refresh = function() {
    this.createContents();
    this.drawAllItems();
};

/* 绘制项目 */
Window_DebugRange.prototype.drawItem = function(index) {
    var rect = this.itemRectForText(index);
    var start;
    var text;
    if (index &lt; this._maxSwitches) {
        start = index * 10 + 1;
        text = 'S';
    } else {
        start = (index - this._maxSwitches) * 10 + 1;
        text = 'V';
    }
    var end = start + 9;
    text += ' [' + start.padZero(4) + '-' + end.padZero(4) + ']';
    this.drawText(text, rect.x, rect.y, rect.width);
};

/* 是否取消触发 */
Window_DebugRange.prototype.isCancelTriggered = function() {
    return (Window_Selectable.prototype.isCancelTriggered() ||
            Input.isTriggered('debug'));
};

/* 处理取消 */
Window_DebugRange.prototype.processCancel = function() {
    Window_Selectable.prototype.processCancel.call(this);
    Window_DebugRange.lastTopRow = this.topRow();
    Window_DebugRange.lastIndex = this.index();
};

/* 设置编辑窗口 */
Window_DebugRange.prototype.setEditWindow = function(editWindow) {
    this._editWindow = editWindow;
};

//-----------------------------------------------------------------------------
// 窗口_调试编辑 
// Window_DebugEdit
//
// 在调试画面上的显示开关和变量的窗口。 
// The window for displaying switches and variables on the debug screen.

function Window_DebugEdit() {
    this.initialize.apply(this, arguments);
}

Window_DebugEdit.prototype = Object.create(Window_Selectable.prototype);
Window_DebugEdit.prototype.constructor = Window_DebugEdit;

/* 初始化 */
Window_DebugEdit.prototype.initialize = function(x, y, width) {
    var height = this.fittingHeight(10);
    Window_Selectable.prototype.initialize.call(this, x, y, width, height);
    this._mode = 'switch';
    this._topId = 1;
    this.refresh();
};

/* 最大项目数 */
Window_DebugEdit.prototype.maxItems = function() {
    return 10;
};

/* 刷新 */
Window_DebugEdit.prototype.refresh = function() {
    this.contents.clear();
    this.drawAllItems();
};

/* 绘制项目 */
Window_DebugEdit.prototype.drawItem = function(index) {
    var dataId = this._topId + index;
    var idText = dataId.padZero(4) + ':';
    var idWidth = this.textWidth(idText);
    var statusWidth = this.textWidth('-00000000');
    var name = this.itemName(dataId);
    var status = this.itemStatus(dataId);
    var rect = this.itemRectForText(index);
    this.resetTextColor();
    this.drawText(idText, rect.x, rect.y, rect.width);
    rect.x += idWidth;
    rect.width -= idWidth + statusWidth;
    this.drawText(name, rect.x, rect.y, rect.width);
    this.drawText(status, rect.x + rect.width, rect.y, statusWidth, 'right');
};

/* 项目名字 */
Window_DebugEdit.prototype.itemName = function(dataId) {
    if (this._mode === 'switch') {
        return $dataSystem.switches[dataId];
    } else {
        return $dataSystem.variables[dataId];
    }
};

/* 项目状态 */
Window_DebugEdit.prototype.itemStatus = function(dataId) {
    if (this._mode === 'switch') {
        return $gameSwitches.value(dataId) ? '[ON]' : '[OFF]';
    } else {
        return String($gameVariables.value(dataId));
    }
};

/* 设置模式 
 * @param {String} mode 模式（switch：开关，variable：变量） 
 */
Window_DebugEdit.prototype.setMode = function(mode) {
    if (this._mode !== mode) {
        this._mode = mode;
        this.refresh();
    }
};

/* 设置顶部 ID */
Window_DebugEdit.prototype.setTopId = function(id) {
    if (this._topId !== id) {
        this._topId = id;
        this.refresh();
    }
};

/* 当前 ID */
Window_DebugEdit.prototype.currentId = function() {
    return this._topId + this.index();
};

/* 更新 */
Window_DebugEdit.prototype.update = function() {
    Window_Selectable.prototype.update.call(this);
    if (this.active) {
        if (this._mode === 'switch') {
            this.updateSwitch();
        } else {
            this.updateVariable();
        }
    }
};

/* 更新开关 */
Window_DebugEdit.prototype.updateSwitch = function() {
    if (Input.isRepeated('ok')) {
        var switchId = this.currentId();
        SoundManager.playCursor();
        $gameSwitches.setValue(switchId, !$gameSwitches.value(switchId));
        this.redrawCurrentItem();
    }
};

/* 更新变量 */
Window_DebugEdit.prototype.updateVariable = function() {
    var variableId = this.currentId();
    var value = $gameVariables.value(variableId);
    if (typeof value === 'number') {
        if (Input.isRepeated('right')) {
            value+;
        }
        if (Input.isRepeated('left')) {
            value--;
        }
        if (Input.isRepeated('pagedown')) {
            value += 10;
        }
        if (Input.isRepeated('pageup')) {
            value -= 10;
        }
        if ($gameVariables.value(variableId) !== value) {
            $gameVariables.setValue(variableId, value);
            SoundManager.playCursor();
            this.redrawCurrentItem();
        }
    }
};</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_示例插件_myplugin_js">示例插件: MyPlugin.js</h2>
<div class="sectionbody">
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-javascript" data-lang="javascript">//=============================================================================
// MyPlugin.js
//=============================================================================

/*:
 * @plugindesc This is plugin description.
 * @author This is author.
 * @help This is help.
 *
 * @param ------Group1------
 * @default 
 *
 * @param ------Group2------
 * @default 
 *
 * @param StringParam
 * @parent ------Group1------
 * @desc This is string type param.
 * @type string
 * @default abc
 *
 * @param NumberParam
 * @parent ------Group1------
 * @desc This is number type param.
 * @type number
 * @min 1
 * @max 100
 * @default 0
 *
 * @param BooleanParam
 * @parent ------Group1------
 * @desc This is boolean type param.
 * @type boolean
 * @on Open
 * @off Close
 * @default true
 *
 * @param VariableParam
 * @parent ------Group1------
 * @desc This is variable type param.
 * @type variable
 * @default 1
 * 
 * @param SelectParam
 * @parent ------Group1------
 * @type select
 * @option Selection1
 * @value 0
 * @option Selection2
 * @value 1
 * @desc This is select type param.
 * @default 0
 *
 * @param FileParam
 * @desc This is file type param.
 * @type file
 * @dir audio/se/
 * @default Absorb1
 * @require 1
 * 
 * @param ActorParam
 * @parent ------Group2------
 * @desc This is actor type param.
 * @type actor
 * @default 1
 *
 * @param ClassParam
 * @parent ------Group2------
 * @desc This is class type param.
 * @type class
 * @default 1
 *
 * @param ItemParam
 * @parent ------Group2------
 * @desc This is item type param.
 * @type item
 * @default 1
 *
 * @param SkillParam
 * @parent ------Group2------
 * @desc This is skill type param.
 * @type skill
 * @default 1
 *
 * @param WeaponParam
 * @parent ------Group2------
 * @desc This is weapon type param.
 * @type weapon
 * @default 1
 *
 * @param ArmorParam
 * @parent ------Group2------
 * @desc This is armor type param.
 * @type armor
 * @default 1
 *
 * @param EnemyParam
 * @parent ------Group2------
 * @desc This is enemy type param.
 * @type enemy
 * @default 1
 *
 * @param TroopParam
 * @parent ------Group2------
 * @desc This is troop type param.
 * @type troop
 * @default 1
 *
 * @param StateParam
 * @parent ------Group2------
 * @desc This is state type param.
 * @type state
 * @default 1
 * 
 * @param AnimationParam
 * @parent ------Group2------
 * @descThis is animation type param.
 * @type animation
 * @default 1
 * 
 * @param TilesetParam
 * @parent ------Group2------
 * @desc This is tileset type param.
 * @type tileset
 * @default 1
 *
 * @param CommonEventParam
 * @desc This is common_event type param.
 * @type common_event
 * @default 1
 *
 */

/*:zh
 * @plugindesc 这是插件描述。
 * @author 这是作者。
 * @help 这是帮助。
 *
 * @param ------分组1------
 * @default  
 *
 * @param ------分组2------
 * @default 
 *
 * @param 文本参数
 * @parent ------分组1------
 * @desc 这是个文本类型的参数。
 * @type string
 * @default abc
 *
 * @param 数字参数
 * @parent ------分组1------
 * @desc 这是个数字类型的参数。
 * @type number
 * @min 1
 * @max 100
 * @default 1
 *
 * @param 布尔值参数
 * @parent ------分组1------
 * @desc 这是个布尔值类型的参数。
 * @type boolean
 * @on 开启
 * @off 关闭
 * @default true
 *
 * @param 变量参数
 * @parent ------分组1------
 * @desc 这是个变量类型的参数。
 * @type variable
 * @default 1
 *
 * @param 选项参数
 * @parent ------分组1------
 * @type select
 * @option 选项1
 * @value 0
 * @option 选项2
 * @value 1
 * @desc 这是个选项类型的参数。
 * @default 0
 *
 * @param 文件参数
 * @desc 这是个文件类型的参数。
 * @type file
 * @dir audio/se/
 * @default Absorb1
 *
 * @param 角色参数
 * @parent ------分组2------
 * @desc 这是个角色类型的参数。
 * @type actor
 * @default 1
 *
 * @param 职业参数
 * @parent ------分组2------
 * @desc 这是个职业类型的参数。
 * @type class
 * @default 1
 *
 * @param 物品参数
 * @parent ------分组2------
 * @desc 这是个物品类型的参数。
 * @type item
 * @default 1
 *
 * @param 技能参数
 * @parent ------分组2------
 * @desc 这是个技能类型的参数。
 * @type skill
 * @default 1
 *
 * @param 武器参数
 * @parent ------分组2------
 * @desc 这是个武器类型的参数。
 * @type weapon
 * @default 1
 *
 * @param 护甲参数
 * @parent ------分组2------
 * @desc 这是个护甲类型的参数。
 * @type armor
 * @default 1
 *
 * @param 敌人参数
 * @parent ------分组2------
 * @desc 这是个敌人类型的参数。
 * @type enemy
 * @default 1
 *
 * @param 敌群参数
 * @parent ------分组2------
 * @desc 这是个敌群类型的参数。
 * @type troop
 * @default 1
 *
 * @param 状态参数
 * @parent ------分组2------
 * @desc 这是个状态类型的参数。
 * @type state
 * @default 1
 * 
 * @param 动画参数
 * @parent ------分组2------
 * @desc 这是个动画类型的参数。
 * @type animation
 * @default 1
 * 
 * @param 图块参数
 * @parent ------分组2------
 * @desc 这是个图块类型的参数。
 * @type tileset
 * @default 1
 *
 * @param 公共事件参数
 * @parent ------分组2------
 * @desc 这是个公共事件类型的参数。
 * @type common_event
 * @default 1
 *
 */
(function() {

    var parameters = PluginManager.parameters('MyPlugin');

    var param1 = parameters['StringParam'] || parameters['文本参数'];
    var param2 = Number(parameters['NumberParam'] || parameters['数字参数']);
    var param3 = JSON.parse(parameters['BooleanParam'] || parameters['布尔值参数']);
    var param4 = Number(parameters['VariableParam'] || parameters['变量参数']);
    var param5 = parameters['FileParam'] || parameters['文件参数'];
    var param6 = parameters['SelectParam'] || parameters['选项参数'];
    var param7 = Number(parameters['CommonEventParam'] || parameters['公共事件参数']);

    var _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
    Game_Interpreter.prototype.pluginCommand = function(command, args) {
        _Game_Interpreter_pluginCommand.call(this, command, args);
        if (command === 'Console_Log') {
            console.log(args);
        } else if (command == 'Alert') {
            alert(args);
        }
    };

    Game_Action.prototype.applyCritical = function(damage) {
        return damage * 4;
    };

    var _Game_Action_applyCritical = Game_Action.prototype.applyCritical;
    Game_Action.prototype.applyCritical = function(damage) {
        var value = _Game_Action_applyCritical.call(this, damage);
        return value + 100;
    };

})();</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_rpg_maker总结">RPG Maker总结</h2>
<div class="sectionbody">
<div class="ulist">
<ul>
<li>
<p><a href="https://consolelog.gitee.io/rmdoc">文档链接</a></p>
<div class="ulist">
<ul>
<li>
<p><a href="https://consolelog.gitee.io/rmdoc/rmmv">RPG Maker MV 文件结构</a>、
<a href="https://space.bilibili.com/86276758">原作者B站空间</a>、
<a href="https://www.bilibili.com/video/BV1dJ41117Tp?spm_id_from=333.999.0.0">原视频</a></p>
</li>
<li>
<p><a href="https://consolelog.gitee.io/rmdoc/rmmv-window">RPG Maker MV 窗口速查表</a>、
<a href="https://space.bilibili.com/86276758">原作者B站空间</a>、
<a href="https://www.bilibili.com/video/BV1dJ41117Tp?spm_id_from=333.999.0.0">原视频</a></p>
</li>
<li>
<p><a href="https://consolelog.gitee.io/rmdoc/rmmv-js">RPG Maker MV 脚本记录</a>、
<a href="https://space.bilibili.com/86276758">原作者B站空间</a>、
<a href="https://www.bilibili.com/video/BV1dJ41117Tp?spm_id_from=333.999.0.0">原视频</a></p>
</li>
</ul>
</div>
</li>
<li>
<p><a href="https://gitee.com/consolelog/rmdoc">源码地址</a></p>
</li>
</ul>
</div>
</div>
</div>
</div>
</body>
</html>